Python – Find index of last occurrence of a search string in a string

Find index of last occurrence of a search string in a 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 of search string (string contains search string)

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 Code Copy

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 of search string (string does not contain search string)

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 Code Copy

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.

Related Tutorials

Code copied to clipboard successfully 👍