The Python String rfind() Method identifies the substring and returns the last index. It returns the index of the string’s rightest matched substring. It returns -1 if there is no such index.
The syntax of the method is: str.rfind(str, start = 0 end = len(string))
Key Points :
• If you cannot locate the passed string in the main string, this returns -1 as output.
• The rfind() method is a built-in python string method, so there are no python modules needed to use it.
• This method is close to the Python rindex() method, which may also be found in a string to locate the highest index of any substring.
• This method is case sensitive; for example, Computer and computer would be deemed two different terms.
We’ll be covering the following topics in this tutorial:
rfind() Parameters
The parameters of this method are defined as follows:
• str: this parameter shows the substring whose highest index in the main string searched.
• start: this is an optional parameter that indicates the start index from which the search begins, and the default value is 0 since the search starts by default.
• end: This is an optional parameter that shows the search ending index.
Return Value from rfind()
• Returns the maximum substring index in the main string.
• If the substring in the main string is not found, it returns -1 as output in that situation.
How to find last occurrence of character in string python
This python method finds the last occurrence of character in string. This function’s advantage is that it returns a “-1” if a substring is not found rather than throwing the error.
Call str.rfind(char) in python to find last occurrence in string.
Below is the python program to demonstrate the rfind() function:
str = 'The Best Learning Resource for Online Education' find = "Online" res = str.rfind(find) print(res)
When we run above the program, the outcome is as follows:
31
Below are several other functions that we can use to work with string in Python 3