如果字符串以指定的后缀结尾,endswith()
方法返回 True
。否则,返回 False
。
示例
message = 'Python is fun'
# check if the message ends with fun
print(message.endswith('fun'))
# Output: True
字符串 endswith() 的语法
endswith()
的语法是
str.endswith(suffix[, start[, end]])
endswith() 参数
endswith()
接受三个参数
- suffix - 要检查的字符串或后缀元组
- start (可选) - 字符串中要检查 suffix 的起始位置。
- end (可选) - 字符串中要检查 suffix 的结束位置。
endswith() 的返回值
endswith()
方法返回一个布尔值。
- 如果字符串以指定的后缀结尾,则返回 True。
- 如果字符串不以指定的后缀结尾,则返回 False。
示例 1:不带 start 和 end 参数的 endswith()
text = "Python is easy to learn."
result = text.endswith('to learn')
# returns False
print(result)
result = text.endswith('to learn.')
# returns True
print(result)
result = text.endswith('Python is easy to learn.')
# returns True
print(result)
输出
False True True
示例 2:带 start 和 end 参数的 endswith()
text = "Python programming is easy to learn."
# start parameter: 7
# "programming is easy to learn." string is searched
result = text.endswith('learn.', 7)
print(result)
# Both start and end is provided
# start: 7, end: 26
# "programming is easy" string is searched
result = text.endswith('is', 7, 26)
# Returns False
print(result)
result = text.endswith('easy', 7, 26)
# returns True
print(result)
输出
True False True
将元组传递给 endswith()
在 Python 中,可以将元组后缀传递给 endswith()
方法。
如果字符串以元组中的任何一项结尾,endswith()
返回 True。否则,返回 False
示例 3:带元组后缀的 endswith()
text = "programming is easy"
result = text.endswith(('programming', 'python'))
# prints False
print(result)
result = text.endswith(('python', 'easy', 'java'))
#prints True
print(result)
# With start and end parameter
# 'programming is' string is checked
result = text.endswith(('is', 'an'), 0, 14)
# prints True
print(result)
输出
False True True
如果你需要检查字符串是否以指定的前缀开头,可以使用 Python 中的 startswith() 方法。
另请阅读