在Python中,str.endswith()
方法是用于检查字符串是否以指定的后缀结束的方法。其语法如下:
str.endswith(suffix[, start[, end]])
suffix
: 必需,表示要检查的后缀。start
: 可选,表示起始位置,默认为 0。end
: 可选,表示结束位置,默认为字符串的长度。
以下是一个简单的示例:
text = "Hello, World!"
# 使用 endswith 检查字符串是否以指定后缀结束
result1 = text.endswith("World!")
result2 = text.endswith("Hello", 0, 5)
print(result1) # 输出 True
print(result2) # 输出 False
在这个例子中,text.endswith("World!")
返回 True
,因为字符串 “Hello, World!” 以 “World!” 结束。而 text.endswith("Hello", 0, 5)
返回 False
,因为在指定的范围内(从索引 0 到 4),字符串并不以 “Hello” 结束。