Python String rindex() Method

Searches the string for a given substring, starting from the right

Usage

The rindex() method searches for the last occurrence of the specified substring sub and returns its index.

If specified substring is not found, it raises ValueError exception.

The optional arguments start and end are used to limit the search to a particular portion of the string.

Syntax

string.rindex(sub,start,end)

Python string rindex() method parameters
ParameterConditionDescription
subRequiredAny string you want to search for
startOptionalAn index specifying where to start the search.
Default is 0.
endOptionalAn index specifying where to stop the search.
Default is the end of the string.

Basic Examples

Example: Find the index of last occurrence of the substring ‘Big’

S = 'Big, Bigger, Biggest'
x = S.rindex('Big')
print(x)    # 13

rindex() method raises ValueError exception, if specified substring is not found in the string.

Example: Find the index of the substring ‘Small’

# ValueError: substring not found
S = 'Big, Bigger, Biggest'
x = S.rindex('Small')
print(x)

If you want to search the string from the middle, specify the start and end parameter.

Example: Search the string from position 2 to 10

S = 'Big, Bigger, Biggest'
x = S.rindex('Big',2,10)
print(x)    # 5

rindex() vs rfind()

The rindex() method is identical to the rfind() method.

The only difference is that the rfind() method returns -1 (instead of raising a ValueError), if the substring is not found.

Example:

# ValueError: substring not found
S = 'Big, Bigger, Biggest'
x = S.rindex('Small')
print(x)
S = 'Big, Bigger, Biggest'
x = S.rfind('Small')
print(x)    # -1