endswith()
是 Python 字符串对象的一个方法,用于检查字符串是否以指定的后缀结尾。
语法如下:
str.endswith(suffix[, start[, end]])
suffix
:要检查的后缀字符串。start
(可选参数):检查的起始位置,默认为 0。end
(可选参数):检查的结束位置,默认为字符串的末尾。
该方法返回一个布尔值,表示字符串是否以指定的后缀结尾。
示例
sentence = "Hello, World!"
# 检查是否以 "World!" 结尾
result = sentence.endswith("World!")
print(result)
# Output: True
# 检查是否以 "Hello" 结尾(从索引 0 到 5)
result = sentence.endswith("Hello", 0, 5)
print(result)
# Output: False
# 检查是否以 "!" 结尾
result = sentence.endswith("!")
print(result)
# Output: True
在这个例子中,endswith()
方法用于检查字符串是否以指定的后缀结尾。可以选择指定起始位置和结束位置以进行部分检查。