Python字符串endswith()

时间:2020-02-23 14:43:24  来源:igfitidea点击:

如果字符串以给定的后缀结尾,则Python字符串endswith()函数将返回" True",否则返回" False"。

Python字符串endswith()

该函数语法为:

str.endswith(suffix[, start[, end]])

后缀可以是字符串,也可以是要在字符串中查找的字符串后缀的元组。

start是一个可选参数,用于指定从何处开始测试的索引。

end是一个可选参数,用于指定测试必须停止的索引。

Python字符串endswith()示例

让我们看一个简单的python字符串endswith()函数示例。

s = 'I Love Python'

print(s.endswith('Python'))  # True

让我们来看一些带有start参数的示例。

s = 'I Love Python'

print(s.endswith('Python', 2))  # True
print(s.endswith('Python', 9))  # False

第一个print语句的起始索引为2,因此测试将使用子字符串" ove Python"。
这就是为什么第一个输出为True的原因。

对于第二个打印语句,子字符串为" hon",但不以" Python"结尾。
因此,输出为False。

让我们来看一些带有start和end参数的示例。

s = 'I Love Python'

print(s.endswith('hon', 7, len(s)))  # True
print(s.endswith('Pyt', 0, 10))  # True
print(s.endswith('Python', 8))  # False

对于第一个打印语句,子字符串为" Python",即以" hon"结尾,因此输出为True。

在第二个打印语句中,子字符串为" I Love Pyt",因此输出为True。

对于第三个print语句,子字符串为" thon",但不以" Python"结尾,因此输出为False。

带有Tuple的Python字符串endswith()示例

让我们看一些以Tuple字符串作为后缀的示例。

s = 'I Love Python'

print(s.endswith(('is', 'Python')))  # True
print(s.endswith(('Love', 'Python'), 1, 6))  # True

对于第一个打印语句,字符串以" Python"结尾,因此输出为True。

对于第二个打印语句,字符串测试从索引位置1开始并在索引位置6处结束(不包括在内)。
因此,子字符串是" Love",以" Love"结尾,因此输出为True。