Python中提供的內置函數中endswith()是用于判斷一個字符串是否以特定的字符串后綴結尾,如果是則返回邏輯值True,否則返回邏輯值False.
該函數與startswith()函數相似,只不過startswith()函數用于判斷一個字符串是否以特定的字符串前綴開始。
Python中的endswith()函數的語法格式如下:
string_object.endswith ( suffix [ , start [ , end ]] )
各參數的含義如下:
該函數的返回值為邏輯值,如果字符串中包含指定的后綴則返回True,否則返回False。
str1 = "武林網VEVB"
str_suffix = "VEVB"
rtn_result = str1.endswith(str_suffix)
print(rtn_result)
輸出:True
rtn_result = "武林網VEVB".endswith("IT")
print(rtn_result)
輸出:False
str1 = "武林網VEVB"
str_suffix = "VEVB"
rtn_result = str1.endswith(str_suffix, 2)
print(rtn_result)
rtn_result = str1.endswith(str_suffix, 3)
print(rtn_result)
rtn_result = str1.endswith(str_suffix, 4)
print(rtn_result)
輸出:
True
True
False
該參數必須是在指定了start參數的前提下才能使用。
str1 = "武林網VEVB"
print(str1.endswith("VEVB", 2, 5))
print(str1.endswith("VEVB", 2, 6))
print(str1.endswith("VEVB", 2, 7))
輸出:
False
False
True
該函數的start參數和end參數同樣可以使用小于0的整數,具體可以見startswith()函數中的相關內容。
str1 = "I am a student"
suffix =("tutor", "teacher", "student", "headteacher")
rtn_result = str1.endswith(suffix)
print(rtn_result)
輸出:True
這里,endswith()函數將會一一比較字符串中是否包含元組中的某一個元素,如果字符串的后綴包含元組中的某一個元素,則返回True.
這個例子要演示文檔上傳處理時的一個情景。程序根據用戶上傳的不同文檔類型,保存到不同的目錄中。
save_path = "Upload//"
upload_file = "年度報表.docx"
if upload_file.lower().endswith((".doc",".docx")):
save_path += "word//" + upload_file
elif upload_file.lower().endswith((".xls", ".xlsx")):
save_path += "excel//" + upload_file
else:
save_path += "others//" + upload_file
print(save_path)
輸出:Upload/word/年度報表.docx
該段程序首先將用戶上傳文件的名稱使用lower()函數轉換為小寫形式 ,然后使用endswith()函數判斷是否某個特定文件的后綴,然后使用 += 運算符把基礎路徑和文件路徑拼接起來。其在Python3.8.2中運行情況:
新聞熱點
疑難解答