Python rindex

The Python rindex method is used to return the index position of the last occurrence of a specified string. The Python rindex function returns ValueError if the specified string is not found.

The index position starts from 0, Not 1. In this Python section, we discuss how to write the string rindex Function with an example, and the syntax is

String_Value.RIndex(Substring, Starting_Position, Ending_Position)
  • Substring: Please specify the string you want to search for.
  • Starting_Position: If you want to specify the starting point (starting position), then Please specify the index value here. If you omit this parameter, the Python string rindex Function considers Zero as a starting position.
  • Ending_Position: If you want to specify the endpoint (Ending position), then Please specify the index value here. If you omit this parameter, then it considers the highest number.

Python rindex method Example

The following set of examples helps you understand the rindex Function.

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)
Python RIndex string function

First, it finds the last occurrence of a substring ‘abc’ inside the Str1 using it and prints the output.

Str2 = Str1.rindex('abc')
print('First Output is = ', Str2)

It allows us to use the Starting index position.

Str4 = Str1.rindex('abc', 12)
print('Third Output is = ', Str4)

The Python rindex function allows us to use Starting and ending indices. By specifying the starting and ending index positions, we can increase performance. The following statement starts looking for ‘abc’ from 2 and ends at position 21.

As we all know, the second abc is in position 22. So, Python returns the index position of the first abc.

Str5 = Str1.rindex('abc', 2, 21)
print('Fourth Output is = ', Str5)

The following String Method statement is returning Value Error because it starts looking for substring ‘Tutorial’ inside the Str1, which does not exist.

Str6 = Str1.rindex('Tutorial')
print('Fifth Output is = ', Str6)