Python String rindex() Method
Python String rindex() method returns the highest index of the substring inside the string if the substring is found. Otherwise, it raises an exception.
Syntax:
str.rindex(sub, start, end)
Parameters:
- sub : It’s the substring which needs to be searched in the given string.
- start : Starting position where sub is needs to be checked within the string.
- end : Ending position where suffix is needs to be checked within the string.
Note: If start and end indexes are not provided then by default it takes 0 and length-1 as starting and ending indexes where ending indexes is not included in our search.
Return:
Returns the highest index of the substring inside the string if substring is found. Otherwise it raises an exception.
Errors and Exceptions:
ValueError: This error is raised when the argument string is not found in the target string.
Example 1
input: text = 'geeks for geeks'
result = text.rindex('geeks')
output: 10
input: text = 'geeks for geeks'
result = text.rindex('ge')
output: 10Python3
# Python code to demonstrate working of rindex()text = 'geeks for geeks'result = text.rindex('geeks')print("Substring 'geeks':", result) |
Output:
Substring 'geeks': 10
Example 2
Python3
# Python code to demonstrate error by rindex()text = 'geeks for geeks'result = text.rindex('pawan')print("Substring 'pawan':", result) |
Error:
Traceback (most recent call last):
File "/home/dadc555d90806cae90a29998ea5d6266.py", line 6, in
result = text.rindex('pawan')
ValueError: substring not foundExample 3
Python3
# Python code to demonstrate working of rindex()# with range providedquote = 'geeks for geeks'# Substring is searched in ' geeks for geeks'print(quote.rindex('ge', 2))# Substring is searched in 0 to 10 rangeprint(quote.rindex('geeks', 0, 10)) |
Output:
10 0


 (2).jpg)
