The rindex Method in Python: Searching for a Substring from the Right

Returns the highest index where the end of a specified substring is found in the original string.

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

  • sub: Substring whose starting index must be determined
  • start=0: Starting index of the slice in the original string where the substring must be found
  • end=None: Ending index of the slice in the original string where the substring must be found

This method is similar to rfind(), but raises an exception if the substring is not found:

my_str = 'barbarian'
my_str.rindex('bar')  # 3
my_str.rindex('bar', 1)  # 3
my_str.rindex('bar', 1, 2)  # ValueError

The optional parameters start and end can take any values supported by slicing, including negative values.