Python String rfind()
rfind() string method is used to return the highest index(right most occurence) of the substring in the given string. By highest index we mean if a given substring is present twice or thrice in a string then the right most occurence or the last occurence of the substring, that index will be returned by the
rfind() method, hence we say that it returns the highest index of the substring.
If the passed string is not found in the main string then this method returns -1 as output.
rfind()method is an inbuilt string method in python, so you do not need any python module to use it.
This method is similar to the Python rindex() method which also can be used to find the highest index of any substring in a given string.
This method is case sensitive, for example it will consider study and Study as two different words.
Below we have a basic syntax of the
rfind() method in Python:
str.rfind(substring, start_index, end_index)
Note: In the above syntax, str denotes the main string, whereas substring is a part of the main string whose index is searched using this method.
The description of the parameters of this method is as follows:
This parameter indicates the substring whose highest index is to be searched in the main string.
This is an optional parameter, which indicates the starting index from where the search begins and its default value is 0, because by default the search starts from the beginning.
This is an optional parameter, which indicates the ending index where the search ends.
rfind(): Returned Values
It returns the highest index of the substring that is found in the main string.
If the substring is not found in the main string, in that case, it returns -1 as output.
rfind(): Basic Example
Below we have an example to show the working of String
str1 = "Hello I love StudyTonight more than I love myself!" str2= "I love Python Python Python" print("String: ", str1, "Highest Index: ", str1.rfind("love", 3, 14)) print("String: ", str2, "Highest Index: ", str2.rfind("Python"))
The Output will be:
String: Hello I love StudyTonight! Highest Index: 8
String: I love Python Highest Index: 21
As you can see in the example above, we have used the beginning and ending index parameters too, as a result of which, even though the word love was present at a higher index too than index 8, but that is not considered because that is out of the given index range.
And in the second string, we have the substring Python 3 times, and the function
rfind() returned the index of the right most occurence, which is the highest index.
Time for a Live Example!
Below we have a live example of
rfind() method in different cases. Let us see the code with its output:
In this tutorial, we learned that the python
rfind() string method is used in order to return the highest index of the substring present in the given main string.