Python endswith 方法如果字符串以指定的子字符串结尾,则返回布尔值 TRUE。否则,它返回 False。当我们需要检查用户输入的结尾项时,字符串 endswith 函数非常有用,它的基本语法是:
String_Value.endswith(Substring, Starting_Position, Ending_Position)
- 子字符串:您要搜索的字符串。
- 起始位置:如果您想为字符串 endswith 函数指定起始索引位置,请在此处指定索引值。
- 结束位置:如果您想指定结束索引位置,请在此处指定索引值。
Python endswith 方法示例
以下示例集可帮助您理解字符串 endswith 函数。首先,我们声明了一个示例文本。接下来,Str2 检查字符串 Str1 是否以“Gateway”结尾,并打印输出。
它还允许我们直接在字符串字面量上使用。因此,我们对 Str3 使用了相同的。Python 字符串 endswith 函数允许我们使用开始和结束索引。通过指定开始和结束索引位置,我们可以提高性能。
Str5 的以下 Python 语句从位置 6 开始查找,并检查关键字“Python”是否位于位置 12。
如果它在结束点找不到指定的字符串,它将返回布尔值 False。以下 Str7 语句返回 False,因为此 字符串方法 开始查找“Python”一词,而且我们都知道 Str1 以“Gateway”结尾。
Str1 = 'Learn Python at Tutorial Gateway';
Str2 = Str1.endswith('Gateway')
print('First Output of a method is = ', Str2)
Str3 = 'Find Tutorial at Tutorial Gateway'.endswith('Gateway')
print('Second Output of a method is = ', Str3)
# Using First Index
Str5 = Str1.endswith('Python', 6, 12)
print('Third Output of a method is = ', Str5)
# Searching for Non existing
Str7 = Str1.endswith('Python')
print('Fourth Output of a method is = ', Str7)
