In this tutorial, we’ll learn what Python string rfind() method is and how to properly use it. We’ll go through multiple Python code examples to understand how rfind method works.
Introduction: Python String rfind() Method
This method returns the highest index value of specified character/substring. It returns -1 if the substring is not found.
Syntax of rfind() Method
string.rfind(substring, startingPoint(optional), endingPoint(optional))
- Python string rfind method can take up to three parameters.
- First parameter is the character/substring whose highest index value is to be searched.
- Second parameter is used to specify the starting point from where the search will start.
- Third parameter is used to specify the ending point of search. These two parameters are actually used to limit the search range. The whole string will be searched if no search limit is specified.
- This method returns -1 if specified character/substring is not found.
- Python string rfind method is case sensitive so a and A will be taken/used as different values. Same goes for other alphabets as well.
Example 1: rfind() Method applied on a Python String
print('Python Programming'.rfind('P')) print('Python Programming'.rfind('p')) print('Python Programming'.rfind('o')) print('Python Programming Python language'.rfind('Python')) print('Python Programming Python language'.rfind('Flutter'))
Output
7 -1 // value not found (p and P are different(case sensitive)) 9 19 -1 // value not found
This is how Python string rfind method works. You can try it with even more examples to better understand the working of this method.
Example 2: rfind() Method with Specified Range
print('Python program'.rfind('Python',5)) // starting point(index) print('Python program'.rfind('program',1,4)) // starting and ending point(index)
Output
-1 -1
In example 1, we’ve specified a starting range that doesn’t include all the characters of the specified substring. As a result, this method returns -1.
In example 2, we’ve specified a starting point and ending point. Ending point ends before the specified substring so as a result, the method returns -1.
Do try it with other examples to properly understand the usage of starting and ending point in Python string rfind method.
Example 3: Python String rfind() Method Return Value
val= 'Python Programming Python Language' returnedVal=val.rfind('Pytho') print(returnedVal)
Output
19 // highest index value of specified substring is 19
We can see that Python string rfind method has returned the highest index value of specified substring.
Conclusion
To conclude this tutorial, hope you now have a detailed practical understanding of how to properly use Python string rfind method. I’d be very happy to receive your feedback on this post. Thank you for reading it.