Python String rfind() Method

By Lenin Mishra

If you prefer to watch Youtube videos over reading blogs, check out our video on Python strings here.

Python String rfind() method

The rfind() method in Python finds the last occurrence of the specified substring. It returns -1 if the value is not found.

Its the opposite of find() method as find() finds the first occurence of a substring.

Syntax of rfind() method
string.rfind(value, start, end)

value: The substring to find(required)
start:	The integer position to start the search. Default is 0.(Optional)
end:	The integer position to end the search. Default is the end of the string.(Optional)
Example

Code/Output

str1 = "Pylenin loves Python and Python loves Pylenin."

# first occurence of "Python"
print(str1.find("Python"))
>>> 14

# last occurence of "Python"
print(str1.rfind("Python"))
>>> 25
Example 2 - A substring that doesn’t exist

Code/Output

str1 = "Pylenin loves Python and Python loves Pylenin."

print(str1.rfind("Apples"))
>>> -1
Example 3 - Last occurence of substring between specified positions

Code/Output

str1 = "Pylenin loves Python and Python loves Pylenin."

# occurence of "Python" between 
# position 20 and 40
print(str1.rfind("Python", 20, 40))
>>> 25

Check out other commonly used Python string methods.

  1. How to create a string in Python?
  2. How to access characters in a Python string?
  3. How to replace characters in a string in Python?
  4. How to concatenate strings in Python?
  5. How to iterate through a string in Python?
  6. Check if a Substring is Present in a Given String in Python
  7. Escape sequences in Python String
  8. Python String Formatting - The Definitive Guide