Python String rindex() Method

The rindex() method is same as the rfind() that returns the index of the last occurence of a substring in the given string. However, unlike the rfind() method, it raises ValueError if the substring is not found.

Syntax:

str.rindex(substr, start, end)

Parameters:

  1. substr: (Required) The substring whose index of the last occurence needs to be found.
  2. start: (Optional) The starting index position from where the search should start. Default is 0.
  3. end: (Optional) The ending index position till where the search should end. Default is the end of the string.

Return Value:

An integer value indicating an index of the last occurence of the specified substring.

The following example demonstrates rindex() method.

Example:
greet = 'Hello World!'
print('Index of H: ', greet.rfind('H'))
print('Index of o: ', greet.rindex('o'))
print('Index of l: ', greet.rindex('l'))
print('Index of World: ', greet.rindex('World'))
Output
Index of H:  0
Index of o:  7
Index of l:  9
Index of World:  6

In the above example, greet.rindex('H') returns the last index of 'Hello World', that is 0 because there no another 'H' in a string. The greet.rindex('o') returns the last index of 'o' from 'Hello World', that is 7.

The rindex() method returns an index of the last occurance only.

Example:
greet='Hello World'
print('Index of l: ', greet.rindex'l'))
print('Index of o: ', greet.rindex('o'))

mystr='tutorialsteacher is a free tutorials website'
print('Index of tutorials: ', mystr.rindex('tutorials'))
Output
Index of l:  9
Index of o:  7
Index of tutorials:  27

The rindex() method performs case-sensitive search. It raises ValueError if a substring is not found. However, the rfind() method returns -1 if substring not found.

Example:
greet='Hello World'
print(greet.rindex('h')) 
Output
Traceback (most recent call last):
    greet.rindex('h')
ValueError: substring not found

Use the start and end parameters to limit the search of a substring between the specified starting and ending indexes.

Example:
greet ='Hello World'
print(greet.rindex('o', 0, 10)) # start searching from 0 till 9th index
print(greet.rindex('o', 0, 5)) # start searching from 0 till 4th index

print(greet.rindex('o', -11, -6)) # start searching from -11th till -6th index
print(greet.rindex('o', -11, -3))# start searching from -11th till -3th index
Output
7
4
4
7

In the above example, greet.rindex('o', 0, 10) returns 7 for 'Hello World'. The greet.rindex('o', 0, 5) limits the searching before 5th index (till 4th index), so it returns 4 for 'Hello'

Want to check how much you know Python?