Last Updated : 07 Jan, 2025
Python String rindex() method returns the highest index of the substring inside the string if the substring is found. Otherwise, it raises ValueError.
Let's understand with the help of an example:
Python
s = 'geeks for geeks'
res= s.rindex('geeks')
print(res)
Syntax of rindex()Note: If start and end indexes are not provided then by default Python String rindex() Method takes 0 and length-1 as starting and ending indexes where ending indexes is not included in our search.
string.rindex(value, start, end)
Parameters:
Return:
If we provide the start and end value to check inside a string, Python String rindex() will search only inside that range.
Example:
Python
a= "ring ring"
# checks for the substring in the range 0-4 of the string
print(a.rindex("ring", 0, 4))
# same as using 0 & 4 as start, end value
print(a.rindex("ring", 0, -5))
b = "101001010"
# since there are no '101' substring after string[0:3]
# thus it will take the last occurrence of '101'
print(b.rindex('101', 2))
rindex() without start and end index
If we don't provide the start and end value to check inside a string, Python String rindex() will search the entire string .
Example:
Python
a = "ring ring"
# search for the substring,
# from right in the whole string
print(a.rindex("ring"))
b = "geeks"
# this will return the right-most 'e'
print(b.rindex('e'))
Output:
5Errors and Exceptions
2
ValueError is raised when the substring is not found within the specified range or the entire string.
Example:
Python
s = 'geeks for geeks'
res = s.rindex('pawan')
print(res)
Exception:
Traceback (most recent call last):
File "/home/dadc555d90806cae90a29998ea5d6266.py", line 6, in
res= s.rindex('pawan')
ValueError: substring not found
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4