Python String rindex() method
Python String rindex() method
The string. rindex() method in Python returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an exception.
Syntax
string.rindex(sub [,start [,end]])
Parameter
sub: This parameter represents the value to search for.
start( Optional): This parameter signifies the substring from where the search is to start and its
default value is 0.
end: This parameter signifies the substring from where to end the search and its default value is the end of the string.
Return
This method returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an exception.
Example 1
# Python program explaining # the string.rindex() method # initializing the String string ="She sells sea shells by the sea shore" # finding the highest index of substring 'sea' in the string index = string.rindex("sea") # printing the index print("The index of 'sea':",index)
Output
The index of 'sea': 28
Example 2
# Python program explaining # the string.rindex() method # initializing the String string ="She sells seashells by the sea shore" # finding the highest index of substring 'by' in the string result = string.rindex('by') if (result != -1): print("Highest index where 'by' occurs:", result) else: print("Doesn't contain substring")
Output
Highest index where 'by' occurs: 20
Example 3
# Python program explaining # the string.rindex() method # initializing the String string ="She sells seashells by the sea shore" # Substring 'se' is searched in the specified string print(string.rindex('se', 10)) # Substring 'h' searched print(string.rindex('h', 2)) # Substring 's' is searched print(string.rindex('s', 10, -1)) # Substring 'hi' searched # will raise a ValueError print(string.rindex('hi'))
Output
27 32 31 Traceback (most recent call last): File "main.py", line 17, in <module> print(string.rindex('hi')) ValueError: substring not found