Python – Find Index of Last Occurrence of Substring in String

Find Index of Last Occurrence of Substring in String

To find the index of last occurrence of substring in string in Python, call rfind() method on the string and pass the substring as argument. The method finds the highest index of the occurrence of substring, and returns the index (an integer).

The syntax to find the index of last occurrence of substring search in the string x is

x.rfind(search)

Examples

1. Find index of last occurrence (string contains substring)

In the following program, we take a string x, and a search string search. The values of x and search are such that x contains search. So, rfind() method must return the index of last occurrence of search in x.

Python Program

x = 'apple is red. some apples are green.'
search = 'apple'

index = x.find(search)

print('Index :', index)
Run

Output

Index : 19

Explanation

apple is red. some apples are green.
                   apple   <- last occurrence
0123..           ..19 is the index of last occurrence

2. Find index of last occurrence (string does not contain substring)

In the following program, we take a string x, and a search string search. The values of x and search are such that x does not contain search. So, rfind() method must return -1.

Python Program

x = 'apple is red. some apples are green.'
search = 'yellow'

index = x.rfind(search)

print('Index :', index)
Run

Output

Index : -1

Summary

In this tutorial of Python Examples, we learned how to find the index of last occurrence of a search string or substring in a string using string method str.rfind(), with the help of well detailed examples.