Python String | rfind()

rfind() method returns the highest index of the substring if found in given string. If not found then it returns -1.

Syntax :

str.rfind(sub, start, end)

Parameters :



sub : It’s the substring which needs to be searched in the given string.
start : Starting position where sub is needs to be checked within the string.
end : Ending position where suffix is needs to be checked within the string.

NOTE : If start and end indexes are not provided then, by default it takes 0 and length-1 as starting and ending indexes where ending indexes is not included in our search.

Return : Returns the highest index of the substring if it is found in given string; if not found, then it returns -1.

Exception :
ValueError : This error is raised in the case when the argument string is not found in the target string.

CODE #1

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate working of rfind()
# in whole string
word = 'geeks for geeks'
  
# Returns highest index of the substring
result = word.rfind('geeks')
print ("Substring 'geeks' found at index :", result )
  
result = word.rfind('for')
print ("Substring 'for' found at index :", result )
  
word = 'CatBatSatMatGate'
  
# Returns highest index of the substring
result = word.rfind('ate')
print("Substring 'ate' found at index :", result)

chevron_right


Output :

Substring 'geeks' found at index : 10
Substring 'for' found at index : 6
Substring 'ate' found at index : 13

 
CODE #2

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate working of rfind()
# in a sub-string
word = 'geeks for geeks'
  
# Substring is searched in 'eeks for geeks'
print(word.rfind('ge', 2))
  
# Substring is searched in 'eeks for geeks' 
print(word.rfind('geeks', 2))
  
# Substring is searched in 'eeks for geeks' 
print(word.rfind('geeks ', 2))
  
# Substring is searched in 's for g'
print(word.rfind('for ', 4, 11))

chevron_right


Output :

10
10
-1
6

 
Practical Application :
Useful in string checking. To check if given substring is present in some string or not.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate working of rfind()
# to search a string
word = 'CatBatSatMatGate'
  
if (word.rfind('Ate') != -1):
    print ("Contains given substring ")
else:
    print ("Doesn't contains given substring")

chevron_right


Output :

Doesn't contains given substring


My Personal Notes arrow_drop_up

pawanasipugmailcom

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.