Python String rindex() Method
Last Updated :
22 Aug, 2022
Python String rindex() method returns the highest index of the substring inside the string if the substring is found. Otherwise, it raises ValueError.
Python String index() Method Syntax
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.
Return: Returns the highest index of the substring inside the string if substring is found. Otherwise it raises an exception.
Python String index() Method Example
Python3
text = 'geeks for geeks'
result = text.rindex('geeks')
print("Substring 'geeks':", result)
|
Output:
Substring 'geeks': 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.
Example 1: Python String rindex() Method 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.
Python3
string = "ring ring"
print(string.rindex("ring", 0, 4))
print(string.rindex("ring", 0, -5))
string = "101001010"
print(string.rindex('101', 2))
|
Output:
0
0
5
Example 2: Python String rindex() Method without start and end index
Python3
string = "ring ring"
print(string.rindex("ring"))
string = "geeks"
print(string.rindex('e'))
|
Output:
5
2
Errors and Exceptions:
ValueError: This error is raised when the argument string is not found in the target string.
Python3
text = 'geeks for geeks'
result = text.rindex('pawan')
print("Substring 'pawan':", result)
|
Exception:
Traceback (most recent call last):
File "/home/dadc555d90806cae90a29998ea5d6266.py", line 6, in
result = text.rindex('pawan')
ValueError: substring not found
Please Login to comment...