Python string.endswith() 函数用法

2023-09-17 22:20:59

如果字符串以指定的后缀(区分大小写)结尾,则 endswith() 函数返回 True,否则返回 False。还可以传递字符串元素元组以检查多个选项。如果字符串以元组的任何元素结尾,则 endswith() 函数返回 True。

它检查从起始索引到结束索引位置的后缀。索引从 0 开始。默认情况下,如果未指定开始和结束索引,它将检查整个字符串。

Synatx:

str.endswith(suffix, start, end)

参数:

  1. 后缀 :(必需)要查找的字符串或字符串元组。
  2. start :(可选)搜索应从哪个开始索引。默认值为 0。
  3. end :(可选)搜索应结束的结束索引。默认为字符串的最后一个索引。

返回值:

如果字符串以指定的后缀结尾,则返回 True,否则返回 False。

下面的示例演示 endswith() 方法。

mystr = 'Python is a  programming language.'
print(mystr.endswith('.')) # returns True
print(mystr.endswith('age.')) # returns True
print(mystr.endswith('language.')) # returns True
print(mystr.endswith(' programming language.')) # returns True
print(mystr.endswith('age')) # returns False, . is missing

输出:

True
True
True
True
False

下面的示例演示如何使用开始和结束参数。

mystr = 'Hello World'
print(mystr.endswith('h', 0, 1)) # is 'H' endswith 'h'? False
print(mystr.endswith('H', 0, 1)) # is 'H' endswith 'H'? True
print(mystr.endswith('e', 0, 2)) # is 'He' endswith 'e'? True
print(mystr.endswith('o', 0, 5)) # is 'Hello' endswith 'o'? True

输出:

False
True
True
True

在上面的示例中,mystr.endswith('h', 0, 1)返回False因为它执行区分大小写的搜索。 mystr.endswith('e', 0, 2)搜索从 0 开始,结束索引 1(结束索引 -1),因此它考虑以"e"结尾的"He"字符串,因此返回 True。

下面的示例包含元组作为参数。

mystr = 'Tutorials Teacher is a free online tutorials website'
print(mystr.endswith(('Tutorials','free','website'))) # returns True
print(mystr.endswith(('Tutorials','free')))  # returns False
print(mystr.endswith(('Tutorials','coding'), 7, 11)) # returns False
mystr.endswith(('Tutorials','coding'), 0, 9) # returns True

输出:

True
False
False
True

在上面的示例中,mystr.endswith(('Tutorials','free','website'))检查字符串是否以指定元组的任何元素结尾 ('Tutorials', 'free', 'website')mystr以"网站"结尾,因此返回 True。mystr.endswith(('Tutorials','coding'), 7, 11)检查从起始索引 7 到结束索引 10 (11-1) 的后缀。

如果将空字符串作为参数传递,则 endswith() 函数将始终返回 True。

mystr = 'Hello World'
print(mystr.endswith(''))
print(mystr.endswith('', 1, 3))

输出:

True
True