Python String rindex() Method

By Lenin Mishra

If you prefer to watch Youtube videos over reading blogs, check out our video on Python strings here.

Python String rindex() method

The rindex() method finds the last occurrence of the specified substring.

If the value is not found, rindex() method raises a ValueError exception.

Its the opposite of index() method as index() finds the position of first occurence of a substring.

Syntax of rindex() method
string.rindex(value, start, end)

value: The substring to find(required)
start:	The integer position to start the search. Default is 0.(Optional)
end:	The integer position to end the search. Default is the end of the string.(Optional)


str1 = "Pylenin loves Python and Python loves Pylenin."

# first occurence of "Python"
>>> 14

# last occurence of "Python"
>>> 25
Example 2 - A substring that doesn’t exist


str1 = "Pylenin loves Python and Python loves Pylenin."

>>> ValueError: substring not found
Example 3 - Last occurence of substring between specified positions


str1 = "Pylenin loves Python and Python loves Pylenin."

# occurence of "Python" between 
# position 20 and 40
print(str1.rindex("Python", 20, 40))
>>> 25

Check out other commonly used Python string methods.

  1. How to create a string in Python?
  2. How to access characters in a Python string?
  3. How to replace characters in a string in Python?
  4. How to concatenate strings in Python?
  5. How to iterate through a string in Python?
  6. Check if a Substring is Present in a Given String in Python
  7. Escape sequences in Python String
  8. Python String Formatting - The Definitive Guide