Python str.endswith() 方法用于判断字符串是否以指定后缀结尾。
语法
s.endswith(suffix, start=0, end=len(s))参数
suffix:后缀字符串或后缀元组。可选 start/end:检查范围。
返回值
返回布尔值:以指定后缀结尾为 True。
示例
print("image.png".endswith(".png")) # True
print("image.png".endswith((".png", ".jpg"))) # True,元组任一
text = "Hello, world."
print(text.endswith(".")) # True
filename = "data.csv"
if filename.endswith(".csv"):
print("是 CSV 文件")输出:
True
True
True
是 CSV 文件注意事项
suffix 传元组可匹配多个后缀,判断文件类型非常方便。