python endswith函数_Python中endswith()函数的使用方法

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 = "翔宇亭IT乐园"

str_suffix = "IT乐园"

rtn_result = str1.endswith(str_suffix)

print(rtn_result)

输出:True

rtn_result = "翔宇亭IT乐园".endswith("IT")

print(rtn_result)

输出:False

(2)指定参数start

str1 = "翔宇亭IT乐园"

str_suffix = "IT乐园"

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 = "翔宇亭IT乐园"

print(str1.endswith("IT乐园", 2, 5))

print(str1.endswith("IT乐园", 2, 6))

print(str1.endswith("IT乐园", 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中运行情况:

202061214514211447.png

20206121448085246.png

如需转载请注明出处:翔宇亭IT乐园(www.biye5u.com)

本文链接地址:http://www.biye5u.com/article/python/2020/6437.html

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值