国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Python > 正文

Python中endswith()函數的使用方法

2023-04-27 19:03:16
字體:
來源:轉載
供稿:網友

Python中提供的內置函數中endswith()是用于判斷一個字符串是否以特定的字符串后綴結尾,如果是則返回邏輯值True,否則返回邏輯值False.

該函數與startswith()函數相似,只不過startswith()函數用于判斷一個字符串是否以特定的字符串前綴開始。

1、endswith()函數的語法形式

Python中的endswith()函數的語法格式如下:

string_object.endswith suffix [ , start [ , end ]] )

2、endswith()函數的參數含義

各參數的含義如下:

  • suffix: 必選參數,用于給出要判斷的后綴字符串,可以是字符串類型,也可以是一個字符串元組;
  • start:可選參數,用于指定字符串搜索的起始位置索引;
  • end:可選參數,用于指定字符串搜索停止位置的索引。

該函數的返回值為邏輯值,如果字符串中包含指定的后綴則返回True,否則返回False

3、使用實例

(1)不指定start和end

str1 = "武林網VEVB"
str_suffix = "VEVB"
rtn_result = str1.endswith(str_suffix)
print(rtn_result)

輸出:True

rtn_result = "武林網VEVB".endswith("IT")
print(rtn_result)

輸出:False

(2)指定參數start

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

(3)指定參數end

該參數必須是在指定了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()函數中的相關內容。

4、suffix參數為元組的情形

str1 = "I am a student"
suffix =("tutor", "teacher", "student", "headteacher")
rtn_result = str1.endswith(suffix)
print(rtn_result)

輸出:True

這里,endswith()函數將會一一比較字符串中是否包含元組中的某一個元素,如果字符串的后綴包含元組中的某一個元素,則返回True.

5、一個實際應用的例子

這個例子要演示文檔上傳處理時的一個情景。程序根據用戶上傳的不同文檔類型,保存到不同的目錄中。

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中運行情況:

Python中判斷上傳文件的類型

Python中endswith()的使用方法

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 大洼县| 玉龙| 益阳市| 汉中市| 大田县| 诸城市| 敖汉旗| 社会| 五河县| 忻城县| 武川县| 从化市| 云林县| 沈丘县| 湛江市| 平顺县| 茌平县| 大宁县| 阳谷县| 延川县| 尼勒克县| 蛟河市| 山西省| 高州市| 衡水市| 元阳县| 宝丰县| 平邑县| 阿拉善左旗| 龙里县| 新乡县| 中卫市| 栾城县| 商都县| 陈巴尔虎旗| 上蔡县| 敦煌市| 肥西县| 林西县| 南涧| 伊宁县|