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.
str.rindex(sub, start, end)
- 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.
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.
input: text = 'geeks for geeks' result = text.rindex('geeks') output: 10 input: text = 'geeks for geeks' result = text.rindex('ge') output: 10
Substring 'geeks': 10
Traceback (most recent call last): File "/home/dadc555d90806cae90a29998ea5d6266.py", line 6, in result = text.rindex('pawan') ValueError: substring not found
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course