Python String rfind() Method – Find Last Occurrence of Substring

Python String rfind() Method

The rfind() method in Python is used to find the last occurrence of a substring in a given string. It returns the highest index where the substring is found, or -1 if it's not found.

Syntax

string.rfind(substring, start, end)

Parameters:

  • substring – The string to search for.
  • start (optional) – The starting index to begin search.
  • end (optional) – The ending index where search stops.

Returns:

  • Index (int) of the last occurrence of the substring.
  • -1 if the substring is not found.

Example 1: Basic Usage of rfind()

text = "hello world, welcome to the world of Python"
index = text.rfind("world")
print(index)
28

Why? The substring "world" occurs twice, and the last one starts at index 28.

Example 2: Substring Not Found

text = "python programming"
print(text.rfind("java"))
-1

Why? Because "java" is not found in the string.

Example 3: Using Start and End Parameters

text = "abc abc abc"
print(text.rfind("abc", 0, 7))
4

Why? It searches only from index 0 to 7. The last "abc" in this range starts at index 4.

Difference Between find() and rfind()

  • find() returns the first occurrence
  • rfind() returns the last occurrence

Use Cases of rfind()

  • Finding the position of the last slash (/) in a file path
  • Getting the extension from the last dot in a filename
  • Parsing or slicing strings based on the last match

Common Mistakes

  • Confusing rfind() with rindex()rindex() raises an error if substring not found, rfind() returns -1.
  • Ignoring optional start and end which can restrict search range.

Practice Problem

Given a string containing multiple email addresses separated by commas, find the last occurrence of “@gmail.com”.

emails = "john@yahoo.com, jane@gmail.com, doe@gmail.com, someone@outlook.com"
print(emails.rfind("@gmail.com"))

Expected Output:

38

Summary

  • rfind() returns the highest index of a substring
  • Returns -1 if the substring is not found
  • Useful when you need to search from the end of the string

Next Steps

Practice with strings that have multiple repeating words. Try restricting the search range with start and end parameters for deeper understanding.