Find Last Occurrence of Substring in Python



In Python, working with strings is a common task in data processing and text analysis. The common operation is finding the last occurrence of a specific substring. It is useful in situations like extracting the domain names or locating the repeated elements in logs.

Python provides several methods to accomplish this; the most commonly used are ?

  • Python rfind() Method
  • Python rindex() Method

Using python rfind() Method

The Python rfind() method is used to find the last occurrence of the substring in the given string; if not found, it returns -1.

Syntax

string.rfind(value, start, end)

Example

Let's look at the following example, where we will consider the basic usage of the rfind().

Open Compiler
str1 = "Welcome to tutorialspoint" index = str1.rfind("t") print("The last index of t in the given string is", index)

Output

The output of the above given example is:

The last index of t in the given string is 24

Uisng python rindex() Method

The Python rindex() method is used to find the last occurrence of a substring in a given string.

This method is similar to the rfind() method, but the difference is that the rfind() method returns -1, if the substring is not found, but the rindex() method raises an exception (Value Error).

Syntax

str.rindex(value, start, end)

Example 1

Consider the following example, where we are going to use the rindex() to find the last occurrence.

Open Compiler
str1 = "Welcome to tutorialspoint" index = str1.rindex('t') print("The last index of t in the given string is",index)

Output

The output of the above example is as follows ?

The last index of t in the given string is 24

Example 2

In the following example, we are going to use rindex() and find the last occurrence of the substring that is not present in the original string and observe the output.

Open Compiler
str1 = "Welcome to tutorialspoint" index = str1.rindex('d') print("The last index of t in the given string is",index)

Output

If we run the above program, it will generate the following output ?

Traceback (most recent call last):
  File "/home/cg/root/67f5acf8d76df/main.py", line 2, in <module>
index = str1.rindex('d')
            ^^^^^^^^^^^^^^^^
ValueError: substring not found
Updated on: 2025-04-11T12:01:39+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements