Python rindex 方法用于返回指定字符串最后一次出现的索引位置。如果找不到指定的字符串,rindex 函数将返回 ValueError。
索引位置从 0 开始,而不是 1。在 Python 部分,我们讨论如何编写带有示例的字符串 rindex 函数,其语法为:
String_Value.RIndex(Substring, Starting_Position, Ending_Position)
- Substring:请指定要搜索的字符串。
- Starting_Position:如果要指定起始点(起始位置),请在此处指定索引值。如果省略此参数,字符串 rindex 函数将从零开始计算。
- Ending_Position:如果要指定终点(结束位置),请在此处指定索引值。如果省略此参数,则它会考虑最高数字。
Python rindex 方法示例
以下示例集将帮助您理解 rindex 函数。
Str1 = 'We are abc working at abc company';
Str2 = Str1.rindex('abc')
print('First Output = ', Str2)
# Performing directly
Str3 = 'Find Tutorial at Tutorial Gateway'.rindex('Tutorial')
print('Second Output = ', Str3)
# Using First Index while finding the String
Str4 = Str1.rindex('abc', 12)
print('Third Output = ', Str4)
# Using First & Second Index while finding the String
Str5 = Str1.rindex('abc', 2, 21)
print('Fourth Output = ', Str5)
# Searching for Not existing Item
Str6 = Str1.rindex('Tutorial')
print('Fifth Output = ', Str6)

首先,它使用它查找子字符串‘abc’在 Str1 中的最后一次出现,并打印输出。
Str2 = Str1.rindex('abc')
print('First Output is = ', Str2)
它允许我们使用起始索引位置。
Str4 = Str1.rindex('abc', 12)
print('Third Output is = ', Str4)
rindex 函数允许我们使用起始和结束索引。通过指定起始和结束索引位置,我们可以提高性能。以下语句开始在位置 2 查找‘abc’,在位置 21 结束。
众所周知,第二个 abc 在位置 22。因此,Python 返回第一个 abc 的索引位置。
Str5 = Str1.rindex('abc', 2, 21)
print('Fourth Output is = ', Str5)
以下字符串方法语句返回 Value Error,因为它开始在 Str1 中查找子字符串‘Tutorial’,而该子字符串不存在。
Str6 = Str1.rindex('Tutorial')
print('Fifth Output is = ', Str6)