如果字符串以指定的值结尾,则endswith()方法返回True。如果不是,则返回False。
endswith()的语法为:
str.endswith(suffix[, start[, end]])
endwith()具有三个参数:
suffix -要检查的后缀字符串或元组
start(可选)- 在字符串中检查suffix开始位置。
end(可选)- 在字符串中检查suffix结束位置。
endswith()方法返回一个布尔值。
字符串以指定的值结尾,返回True。
如果字符串不以指定的值结尾,则返回False。
text = "Python is easy to learn."
result = text.endswith('to learn')
# 返回 False
print(result)
result = text.endswith('to learn.')
# 返回 True
print(result)
result = text.endswith('Python is easy to learn.')
# 返回 True
print(result)运行该程序时,输出为:
False True True
text = "Python programming is easy to learn."
# start 参数: 7
# "programming is easy to learn." 为被检索的字符串
result = text.endswith('learn.', 7)
print(result)
# 同时传入 start 和 end 参数
# start: 7, end: 26
# "programming is easy" 为被检索的字符串
result = text.endswith('is', 7, 26)
# 返回 False
print(result)
result = text.endswith('easy', 7, 26)
# 返回 True
print(result)运行该程序时,输出为:
True False True
可以在Python中将元组做为指定值传递给endswith()方法。
如果字符串以元组的任何项目结尾,则endswith()返回True。如果不是,则返回False
text = "programming is easy"
result = text.endswith(('programming', 'python'))
# 输出 False
print(result)
result = text.endswith(('python', 'easy', 'java'))
#输出 True
print(result)
# 带 start 和 end 参数
# 'programming is' 字符串被检查
result = text.endswith(('is', 'an'), 0, 14)
# 输出 True
print(result)运行该程序时,输出为:
False True True
如果需要检查字符串是否以指定的前缀开头,则可以在Python中使用startswith()方法。