How to Find the Last Occurrence of a Substring in a String Using Python?

In this tutorial, I will explain how to find the last occurrence of a substring in a string using Python. As a software developer working on a text processing tool for a legal firm, I needed to extract the last reference to a specific clause in lengthy contract documents. I researched more about this topic, and I will share my findings in this article with examples and screenshots of executed example code.

Find the Last Occurrence of a Substring in a String Using Python

Python provides various ways to accomplish this task. Let us see some important methods.

Read How to Iterate Through a String in Python?

Method 1. Use rfind() Method

The rfind() method in Python returns the highest index where the substring is found. If the substring is not found, it returns -1.

text = "The United States is a large country, and the states have diverse laws."
substring = "states"

last_index = text.rfind(substring)
print(f"Last occurrence of 'states' is at index: {last_index}")

Output:

Last occurrence of 'states' is at index: 46

I have executed the above example code and added the screenshot below.

Find the Last Occurrence of a Substring in a String Using Python

The rfind() method is ideal for quickly finding the last occurrence of a substring without raising an error if not found. It’s simple and efficient for straightforward substring searches.

Read How to Add Characters to a String in Python?

Method 2. Use rindex() Method

Python rindex() method is similar to rfind(), but it raises a ValueError if the substring is not found.

text = "The United States is a large country, and the states have diverse laws."
substring = "states"

try:
    last_index = text.rindex(substring)
    print(f"Last occurrence of 'states' is at index: {last_index}")
except ValueError:
    print("Substring not found")

Output:

Last occurrence of 'states' is at index: 46

I have executed the above example code and added the screenshot below.

How to Find the Last Occurrence of a Substring in a String Using Python

The rindex() method functions similarly to rfind(), but it raises an exception when the substring is not found, making it suitable for scenarios where you need to handle missing substrings with custom error handling.

Read How to Escape Curly Braces in Python Format Strings?

Method 3. Use re(Regular Expressions)

You can use the re module to find the last occurrence of a pattern in a string by searching from the end.

import re

text = "The United States is a large country, and the states have diverse laws."
substring = "states"

last_occurrence = re.search(r"(.*)states", text)
if last_occurrence:
    print(f"Last occurrence of 'states' is at index: {last_occurrence.end(1)}")

Output:

Last occurrence of 'states' is at index: 46

I have executed the above example code and added the screenshot below.

Find the Last Occurrence of a Substring in a String Using Python re

The re module provides flexibility when dealing with more complex patterns or when you need to search from the end of the string in more customizable ways.

Read How to Parse a String in Python?

Handle Case-Insensitivity

By default, both the rfind() and rpartition() methods are case-sensitive. If you want to perform a case-insensitive search, you can convert both the string and the substring to lowercase before applying the methods. Here’s an example:

comment = "I absolutely love the new iPhone! It's a game-changer in terms of performance and camera quality."
keyword = "iPhone"

comment = comment.lower()
keyword = keyword.lower()

last_occurrence_index = comment.rfind(keyword)

if last_occurrence_index != -1:
    print(f"The last occurrence of '{keyword}' (case-insensitive) is at index {last_occurrence_index}.")
else:
    print(f"The keyword '{keyword}' was not found in the comment (case-insensitive).")

In this example, we convert both the comment and keyword to lowercase using the lower() method before applying the rfind() method. This ensures that the search is case-insensitive.

Read How to Add Line Breaks in Python Strings?

Conclusion

In this tutorial, I have explained how to find the last occurrence of a substring in a string using Python. I discussed methods such as using the rfind() method, rindex() method, and re(regular expression). I also discussed how to handle case insensitivity.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.