endswith()函数
描述:判断字符串是否以指定字符或子字符串结尾。
语法:str.endswith("suffix", start, end) 或
str[start,end].endswith("suffix") 用于判断字符串中某段字符串是否以指定字符或子字符串结尾。
—> bool 返回值为布尔类型(True,False)
suffix — 后缀,可以是单个字符,也可以是字符串,还可以是元组("suffix"中的引号要省略,常用于判断文件类型)。
start —索引字符串的起始位置。
end — 索引字符串的结束位置。
str.endswith(suffix) star默认为0,end默认为字符串的长度len(str)
注意:空字符的情况。返回值通常为True
1 str = "i love python" 2 print("1:",str.endswith("n")) 3 print("2:",str.endswith("python")) 4 print("3:",str.endswith("n",0,6))# 索引 i love 是否以“n”结尾。 5 print("4:",str.endswith("")) #空字符 6 print("5:",str[0:6].endswith("n")) # 只索引 i love 7 print("6:",str[0:6].endswith("e")) 8 print("7:",str[0:6].endswith("")) 9 print("8:",str.endswith(("n","z")))#遍历元组的元素,存在即返回True,否者返回False 10 print("9:",str.endswith(("k","m"))) 11 12 13 #元组案例 14 file = "python.txt" 15 if file.endswith("txt"): 16 print("该文件是文本文件") 17 elif file.endswith(("AVI","WMV","RM")): 18 print("该文件为视频文件") 19 else: 20 print("文件格式未知")
1: True 2: True 3: False 4: True 5: False 6: True 7: True 8: True 9: False 该文件是文本文件
原文链接:https://blog.csdn.net/qq_40678222/article/details/83033587
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?