跳到主要内容

Python String endswith() 方法

endswith() 方法如果字符串以指定的后缀结尾,则返回 True。如果不是,则返回 False

示例

message = 'Python is fun'

# 检查消息是否以 fun 结尾
print(message.endswith('fun'))

# 输出: True

String 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')
# 返回 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

示例 2:带有 start 和 end 参数的 endswith()

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

向 endswith() 传递元组

可以向 Python 中的 endswith() 方法传递一个元组后缀。

如果字符串以元组中的任何项结尾,endswith() 返回 True。如果不是,则返回 False

示例 3:带有元组后缀的 endswith()

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() 方法