endswith函數用于判斷字符串是否以指定的后綴結尾,它的使用方法如下:
string.endswith(suffix[, start[, end]])
其中,string
是要檢查的字符串,suffix
是要檢查的后綴。start
和end
是可選參數,用于指定要檢查的字符串的起始和結束位置。
下面是一些使用示例:
string = "Hello, World!"
# 檢查字符串是否以"World!"結尾
result = string.endswith("World!")
print(result) # 輸出:True
# 檢查字符串是否以"Hello"開頭
result = string.endswith("Hello")
print(result) # 輸出:False
# 檢查字符串中從索引2開始的子字符串是否以"World!"結尾
result = string.endswith("World!", 2)
print(result) # 輸出:False
# 檢查字符串中從索引2到索引13的子字符串是否以"World!"結尾
result = string.endswith("World!", 2, 13)
print(result) # 輸出:True
注意:endswith
函數區分大小寫。如果要忽略大小寫,可以先將字符串轉換為小寫或大寫,然后再進行判斷。