endwith() 可以「判断」字符串是否以指定内容「结尾」。
语法
1 | string.endwith( str , start, end ) |
参数
- str :(必选,字符串或元组)指定字符串或元素
- start :(可选)开始的索引,默认值0
- end :(可选)结束的索引,默认值-1
返回值
- 以指定内容结尾返回 True
- 不以指定内容结尾返回 False
实例:判断字符串是否以 ‘world’ 结尾
1 | print ( 'hello world' .endswith( 'world' )) |
输出:
True
1、指定范围
设置开始和结束的「索引」来指定范围,索引从0开始。
只设置「开始」的索引,默认检查到字符串末尾,即[start,末尾]
1 | print ( 'hello world' .endswith( 'world' , 1 )) |
输出:
True
同时设置「开始」、「结束」的索引,可以检测字符串的某个范围内是否以指定内容结尾。
1 | print ( 'hello world' .endswith( 'world' , 0 , 5 )) |
输出:
False
从输出结果可以发现,字符串(0~5)索引是‘hello ’,不以‘world’结尾,所以返回False。
除了在 endwith() 参数中设置索引,还可以通过字符串的索引来指定范围
1 | print ( 'hello world' [ 0 : 5 ].endswith( 'world' )) |
输出:
False
2、str可以传入元组
str 参数只能是字符串或者元祖(元素都是字符串类型),否则会报错 TypeError: endswith first arg must be str or a tuple of str
传入元素都是字符串的类型的「元祖」,会自动遍历并判断字符串是否以元组中的元素结尾,只要满足一个,就返回True;全部不满足,就返回False。
1 2 | print ( 'hello world' .endswith(( 'world' , 'a' ))) print ( 'hello world' .endswith(( 'b' , 'a' ))) |
输出:
True
False
实例:文件后缀名黑名单
1 2 3 4 5 | file_name = 'shell.php' if file_name.endswith(( 'php' , 'jsp' , 'asp' )): print ( '被禁止的文件类型,请重新上传' ) else : print ( '上传成功' ) |
如果只有「列表」,可以转成数组再判断
1 2 3 | list1 = [ 'world' , 'a' , 'b' ] tuple1 = tuple (list1) print ( 'hello world' .endswith(tuple1)) |
输出:
True
3、空字符串为真
判断字符串是否以 空字符串””结尾时,会返回True。
1 2 | print ( 'hello world' .endswith('')) print ( '*&ab31' .endswith('')) |
输出:
True
True
「空格」就不行了,会返回False
1 | print ( 'hello world' .endswith( ' ' )) |
输出:
False
4、大小写敏感
endwith() 判断时,区分「大小写」,这导致我们匹配不到一些文件后缀名,比如下面这样会返回False
1 2 | file_name = 'shell.PHP' print (file_name.endswith( 'php' )) |
输出:
False
我们可以先 lower() 转成小写,再进行判断
1 2 | file_name = 'shell.pHp' print (file_name.lower().endswith( 'php' )) |
输出:
True
到此这篇关于Python endswith()函数的具体使用的文章就介绍到这了,更多相关Python endswith()内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!