Find index of first occurrence of substring in Python String

avatar

Borislav Hadzhiev

Last updated: Jul 7, 2022

banner

Photo from Unsplash

Find index of first occurrence of substring in Python String #

Use the str.find() method to find the index of the first occurrence of a substring in a string. The str.find() method returns the index of the first occurrence of the provided substring in the string, or -1 if the substring is not present in the string.

main.py
my_str = 'apple, avocado' index_1 = my_str.find('a') print(index_1) # 👉️ 0 # ----------------------------------- index_2 = my_str.index('a') print(index_2) # 👉️ 0

The str.find method returns the index of the first occurrence of the provided substring in the string.

main.py
print('test'.find('t')) # 👉️ 0
The method returns -1 if the substring is not found 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, avocado' index = my_str.find('a') if index != -1: print(my_str[index]) # 👉️ 'a' else: raise IndexError('Provided substring not in string')

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

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

main.py
my_str = 'apple, avocado' index = my_str.index('a') print(index) # 👉️ 0

The str.index method returns the index of the first occurrence of the provided substring in the string.

The method raises a ValueError if the substring is not found in the string.

main.py
my_str = 'apple, avocado' # ⛔️ ValueError: substring not found index = my_str.index('z')
The str.index() method is very similar to str.find() 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, avocado' try: index = my_str.index('z') except ValueError: # 👇️ this runs print('provided substring not in string')

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

main.py
my_str = 'apple, avocado' try: index = my_str.index('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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.