Python 中的 endswith() 方法是一种字符串方法,如果字符串以指定的后缀结尾,则返回 True,否则返回 False。它用于检查字符串是否以特定子字符串结尾。
参数值
| 参数 | 说明 |
|---|---|
| suffix |
|
| start |
|
| end |
|
返回值
endswith() 方法返回一个 bool 值:True 或 False。
如何在 Python 中使用 endswith()
示例 1
如果字符串以指定的后缀结尾,则 endswith() 方法返回 True,否则返回 False。
word = 'Hello World'
print(word.endswith('World'))
示例 2
endswith() 方法还可以采用一个后缀元组作为参数,以检查字符串是否以其中任何一个结尾。
file_name = 'document.txt'
print(file_name.endswith(('.txt', '.pdf')))
示例 3
默认情况下,endswith() 方法区分大小写,但你可以通过将字符串转换为小写来使用不区分大小写的比较。
text = 'Python Programming'
print(text.lower().endswith('programming'))