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 ValueError.
Let’s understand with the help of an example:
s = 'geeks for geeks'
res= s.rindex('geeks')
print(res)
Output
10
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.
Table of Content
Syntax of rindex()
string.rindex(value, start, end)
Parameters:
- value : Part that we are searching for.
- start (optional): Index where the search begins (default is 0).
- end (optional): Index where the search ends (default is the string’s length).
Return:
- It returns the highest index of the substring inside the string if substring is found. Otherwise it raises an exception.
rindex() with start or end index
If we provide the start and end value to check inside a string, Python String rindex() will search only inside that range.
Example:
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))
Output
0 0 5
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:
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:
5
2
Errors and Exceptions
ValueError is raised when the substring is not found within the specified range or the entire string.
Example:
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