Python String rindex()

The syntax of rindex() is:

str.rindex(sub[, start[, end]] )

rindex() Parameters

rindex() method takes three parameters:

  • sub - substring to be searched in the str string.
  • start and end(optional) - substring is searched within str[start:end]

Return Value from rindex()

  • If substring exists inside the string, it returns the highest index in the string where the substring is found.
  • If substring doesn't exist inside the string, it raises a ValueError exception.

rindex() method is similar to rfind() method for strings.

The only difference is that rfind() returns -1 if the substring is not found, whereas rindex() throws an exception.


Example 1: rindex() With No start and end Argument

Output

Substring 'let it': 22
Traceback (most recent call last):
  File "...", line 6, in <module>
    result = quote.rindex('small')
ValueError: substring not found

Note: Index in Python starts from 0 and not 1.


Example 2: rindex() With start and end Arguments

Output

25
18
Traceback (most recent call last):
  File "...", line 10, in <module>
    print(quote.rindex('o small ', 10, -1))
ValueError: substring not found