欢迎访问宙启技术站
智能推送

Python中的endswith函数:检查字符串是否以指定的后缀结束

发布时间:2023-06-13 03:02:22

Python中的endswith函数是一种非常常用的字符串函数,它可以用来检查一个字符串是否以指定的后缀结束。endswith()函数的语法形式如下:

str.endswith(suffix[, start[, end]])

参数suffix为要检查的后缀,若str以suffix为结尾,则返回True;否则返回False。

参数start和end用于指定切片的范围,其中start表示切片的起始位置,end表示切片的结束位置。

endswith函数的返回值为布尔值,即True或False。

下面我们来看一些具体的使用方法。

1.检查字符串是否以指定后缀结束:

str = "Hello,World!"
print(str.endswith("d!")) # True
print(str.endswith("World!")) # True
print(str.endswith("o")) # False

2.检查字符串在特定范围内是否以指定后缀结束:

str = "Hello,World!"
print(str.endswith("o",0,4)) # True

3.检查字符串在特定范围内是否以指定后缀结束没有指定end默认到字符串的结尾:

str = "Hello,World!"
print(str.endswith("World!",0,8)) # True

4.检查一个文件是否是指定类型:

import os
file_name = "test.pdf"
if file_name.endswith(".pdf"):
    print("This is a PDF file!")
else:
    print("This is not a PDF file!")

endswith函数非常方便实用,特别是在文件处理和数据清洗中常常使用。除此之外,Python还有很多其他的字符串函数,比如startswith()函数、find()函数、replace()函数等等,这些函数都可以用来方便地处理字符串。需要根据不同的需求灵活选择适合自己的字符串函数。