Find index of last occurrence of substring in Python String

avatar

Borislav Hadzhiev

Last updated: Jul 7, 2022

banner

Check out my new book

Find index of last occurrence of substring in Python String #

Use the str.rfind() method to find the last occurrence of a substring in a string, e.g. my_str.rfind('a'). The rfind() method returns the highest index where the provided substring is found in the string.

main.py
my_str = 'apple, apricot' index_1 = my_str.rfind('a') print(index_1) # 👉️ 7 # ----------------------------------- index_2 = my_str.rindex('a') print(index_2) # 👉️ 7

We used the str.rfind() method to get the index of the last occurrence of a character in a string.

The str.rfind method returns the highest index in the string where the provided substring is found.

main.py
print('test'.rfind('t')) # 👉️ 3

The method returns -1 if the substring is not contained in the string.

You can handle the scenario where the substring is not present in the string with an if/else statement.

main.py
my_str = 'apple, apricot' index = my_str.rfind('a') if index != -1: result = my_str[index:] else: result = my_str print(result) # 👉️ 'apricot'

You can also raise an exception in the else block.

main.py
my_str = 'apple, apricot' index = my_str.rfind('Z') if index != -1: result = my_str[index:] else: # 👇️ this runs raise IndexError('Provided character not in string')

Alternatively, you can use the str.rindex() method.

Use the str.rindex() method to find the index of the last occurrence of a substring in a string, e.g. index = my_str.rindex('a'). The rindex() method returns the highest index of the provided substring in the string.

main.py
my_str = 'apple, apricot' index = my_str.rindex('a') print(index) # 👉️ 7

The str.rindex method returns the highest index in the string where the provided substring is found.

main.py
print('test'.rindex('t')) # 👉️ 3

The method raises ValueError when the provided substring is not found in the string.

main.py
my_str = 'apple, apricot' # ⛔️ ValueError: substring not found index = my_str.rindex('z')
The str.rindex() method is very similar to str.rfind() but it raises ValueError, instead of returning -1 if the substring is not present in the string.

You can use a try/except block if you need to handle the error in any way.

main.py
my_str = 'apple, apricot' try: index = my_str.rindex('z') except ValueError: # 👇️ this runs print('specified substring not in string')

You can use the pass statement if you just want to ignore the error.

main.py
my_str = 'apple, apricot' try: index = my_str.rindex('z') except ValueError: # 👇️ this runs pass

The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.

Use the search field on my Home Page to filter through my more than 3,000 articles.