rfind() method in Python

In this tutorial, we will learn how to use the rfind() method in Python with some simple examples.

rfind() method in Python:

The following are the basic points of the rfind method.

  • rfind() is a string method that will find the Last occurrence of the substring which is the last match in the string.
  • This method searches a string from left to right to find the substring and returns the index position of the last match.
  • The method returns -1 if the search key does not find in the string.
  • rfind() method takes 3 parameters.

Syntax of rfind() method:

‘String’.rfind(‘Search key’,Start index,Stop index)
‘Search key’ is the string that will be searched for in the string. If the search key is found in the string object then Python will return an index position of the last match. The search is case sensitive.
Start index: The start index is where the rfind string method will start the search for the search key. if no start index is given then by default it takes the beginning of the string.
Stop index: the stop index is where the rfind string method will stop the search for the search key.

points to remember:
1. By default start index is’0’and stop index is ‘length-1’.
2. It takes spaces.
3. The substring search is case sensitive.


#python code
>>>a='learn python from codespeedy'.rfind('c')



EXPLANATION: Here the rfind()  method finds  ‘c’ at 18th index


#python code
>>>a='learn python from codespeedy'.rfind('n') 


EXPLANATION: rfind() method finds the last ‘n’ in the strings


#python code
>>>a= 'learn python from codespeedy'.rfind('n',1,5)


EXPLANATION: The rfind() method returns 4 because here we provided a search key ‘n ‘, start index ‘1’and a stop index ‘5’ so the rfind() method searches between the indices 1 and 5.


#python code
>>>a= 'learn python from codespeedy'.rfind('z')


EXPLANATION: Here the search key ‘z’ is not there in the string hence it returns -1.

Also read: Set operations in Python

Leave a Reply

Your email address will not be published. Required fields are marked *