Python String rfind() Method

The rfind() method returns the highest index of the specified substring (the last occurrence of the substring) in the given string. If the substring is not found, then it returns -1.

Syntax:

str.rfind(substr, start, end)

Parameters:

  1. substr: (Required) The substring whose index of the last occurence needs to be found.
  2. start: (Optional) The starting index position from where the search should start. Default is 0.
  3. end: (Optional) The ending index position till where the search should end. Default is the end of the string.

Return Value:

Returns an integer value indicating an index of the last occurence of the specified substring.

The following example demonstrates rfind() method.

Example:
greet = 'Hello World!'
print('Index of H: ', greet.rfind('H'))
print('Index of o: ', greet.rfind('o'))
print('Index of l: ', greet.rfind('l'))
print('Index of World: ', greet.rfind('World'))
Output
Index of H:  0
Index of o:  7
Index of l:  9
Index of World:  6

In the above example, greet.rfind('H') returns the last index of 'Hello World', that is 0 because there no another 'H' in a string. The greet.rfind('o') returns the last index of 'o' from 'Hello World', that is 7.

The rfind() method returns an index of the last occurance only.

Example:
greet='Hello World'
print('Index of l: ', greet.rfind'l'))
print('Index of o: ', greet.rfind('o'))

mystr='tutorialsteacher is a free tutorials website'
print('Index of tutorials: ', mystr.rfind('tutorials'))
Output
Index of l:  9
Index of o:  7
Index of tutorials:  27

The rfind() method performs case-sensitive search. It returns -1 if a substring is not found.

Example:
greet='Hello World'

print(greet.rfind('H')) 
print(greet.rfind('h')) 
print(greet.rfind('hello')) 
Output
0
-1
-1

Use the start and end parameters to limit the search of a substring between the specified starting and ending indexes.

Example:
greet ='Hello World'
print(greet.rfind('o', 0, 10)) # start searching from 0 till 9th index
print(greet.rfind('o', 0, 5)) # start searching from 0 till 4th index

print(greet.rfind('o', -11, -6)) # start searching from -11th till -6th index
print(greet.rfind('o', -11, -3))# start searching from -11th till -3th index
Output
7
4
4
7

In the above example, greet.rfind('o', 0, 10) returns 7 for 'Hello World'. The greet.rfind('o', 0, 5) limits the searching before 5th index (till 4th index), so it returns 4 for 'Hello'

Want to check how much you know Python?