Python rfind 方法用于返回指定字符串最后一次出现的索引位置。如果找不到指定的字符串,rfind 方法将返回 -1。在本节中,我们将通过一个示例讨论如何编写 rfind 函数,其语法是:
String_Value.rfind(Substring, Starting_Position, Ending_Position)
- 子字符串:您要搜索的字符串。
- 起始位置:如果您想指定起始索引位置,请在此处指定索引值。如果省略此参数,Python rfind 函数将从零作为起始位置。
- 结束位置:如果您想指定终点(结束位置),请在此处指定索引值。如果省略此参数,它将考虑最高数字。
Python rfind 方法示例
以下示例集可帮助您理解 rfind 函数。索引位置从 0 开始,而不是 1。对于 Str2,它使用 rfind 函数查找子字符串 'abc' 在 Str1 中的最后一次出现并打印输出。如果它在 Str1 中找不到指定的字符串,它将返回 -1。这就是为什么 Str4 返回 -1。
它允许我们使用起始索引位置。对于 Str5,我们使用 5 作为起始点。rfind 函数还允许我们使用起始和结束索引。通过指定起始和结束索引位置,我们可以提高性能。
以下 字符串方法 语句从索引位置 2 开始查找 'abc',并在索引 21 处结束。正如我们所知,'abc' 的最后一次出现是在位置 22,但 Python 函数在 21 处停止,因此返回位置 7 的 'abc'。
Str1 = 'We are abc working at abc company';
Str2 = Str1.rfind('abc')
print('First Output = ', Str2)
# Performing directly
Str3 = 'Find Tutorial at Tutorial Gateway'.rfind('Tutorial')
print('Second Output = ', Str3)
# Searching for Not existing Item
Str4 = Str1.rfind('Tutorial')
print('Third Output = ', Str4)
# Using First Index while finding the String
Str5 = Str1.rfind('abc', 5)
print('Fourth Output = ', Str5)
# Using First & Second Index while finding the String
Str7 = Str1.rfind('abc', 2, 21)
print('Sixth Output = ', Str7)
