Skip to main content

rindex()

The rindex() method in Python is a string method used to find the last occurrence of a substring within a string. It returns the highest index where the substring is found, starting the search from the end of the string. If the substring is not found, a ValueError is raised.

Parameter Values

Parameter Description
sub

The substring you want to find in the string.

start

Optional. The start index from which the search should begin.

end

Optional. The end index at which the search should end.

Return Values

The rindex() method returns an int indicating the highest index of the substring.

How to Use rindex() in Python

Example 1:

The rindex() method returns the highest index of the substring in the string.

sentence = 'Hello, this is a sentence. This is a python example.'
index = sentence.rindex('is')
print(index)
Example 2:

If the substring is not found in the string, the rindex() method raises a ValueError.

word = 'apple'
try:
    index = word.rindex('banana')
except ValueError as e:
    print(e)
Example 3:

The rindex() method can also take optional start and end arguments to specify the search range.

sentence = 'Python is a great programming language'
index = sentence.rindex('a', 0, -10)
print(index)