Python String rfind() method
The string. rfind() method in Python returns the highest index in the string if the substring sub is found else it returns -1 if the substring is not found.
Syntax
string.rfind(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 in the string is the substring sub is found else it returns -1 if the substring is not found.
Example 1
# Python program explaining # the string.rfind() 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.rfind("sea") # printing the index print("The index of 'sea':",index)
Output
The index of 'sea': 28
Example 2
# Python program explaining # the string.rfind() method # initializing the String string ="She sells seashells by the sea shore" # finding the highest index of substring 'by' in the string result = string.rfind('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.rfind() method # initializing the String string ="She sells seashells by the sea shore" # Substring 'se' is searched in the specified string print(string.rfind('se', 10)) # Substring 'h' searched print(string.rfind('h', 2)) # Substring 's' is searched print(string.rfind('s', 10, -1)) # Substring 'hi' searched # will return -1 as the substring 'hi' is not present print(string.rfind('hi'))
Output
27 32 31 -1