In this tutorial, we will be exploring the Python string method
rfind(). This is a built-in function in Python that returns the highest index of the substring if found in a given string. If it’s not found, it returns -1.
Usage of rfind() Method
The syntax for using the
rfind() method is as follows:
string.rfind(value, start, end)
This method takes three parameters:
- value: The value you want to search for.
- start (optional): Where to start the search. Default is 0.
- end (optional): Where to end the search. Default is to the end of the string.
A Simple Example of rfind() Method
text = "Hello world, welcome to my world" index = text.rfind("world") print(index) # Output: 24
In this example, we are searching for ‘world’ in our text. The
rfind() method starts searching from right and finds ‘world’ at position 24 which is returned as output.
Detailed Walkthrough with rfind() Method
If you want to specify where Python should start and end looking for your specified value, you can add start and end parameters:
text = "Hello world, welcome to my world" index = text.rfind("world", 10, 30) print(index) # Output: 24
In this example, Python starts looking for ‘world’ at position 10 and stops at position 30. The
rfind() method finds ‘world’ at position 24 which is returned as output.
rfind() method is a powerful tool in Python that allows you to find the highest index of a substring in a string. It’s important to remember that if the substring isn’t found, the method will return -1. This tutorial should provide you with all the knowledge you need to use this function effectively in your own code.