ValueError: substring not found in Python

avatar

Borislav Hadzhiev

Last updated: Apr 24, 2022

banner

Photo from Unsplash

ValueError: substring not found in Python #

The Python "ValueError: substring not found" occurs when we pass a value that doesn't exist in the string to the str.index() method. To solve the error, use the find() method instead, e.g. my_str.find('z'), or handle the error using a try/except block.

valueerror substring not found

Here is an example of how the error occurs.

main.py
my_str = 'apple' # ⛔️ ValueError: substring not found idx = my_str.index('z')

The substring we passed to the index method is not contained in the string, which caused the ValueError.

One way to get around this is to use the str.find() method instead.

main.py
my_str = 'apple' idx = my_str.find('z') print(idx) # 👉️ -1

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

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

Alternatively, you can check if the substring is present in the string before calling the index() method.

main.py
my_str = 'apple' if 'z' in my_str: idx = my_str.index('z') print(idx) else: # 👇️ this runs print('substring is not in string')

The in operator tests for membership. For example, x in s evaluates to True if x is a member of s, otherwise it evaluates to False.

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.

You can also use a try/except block to handle the scenario where the substring is not found in the string.

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

We call the index() method on the string and if a ValueError is raised, the except block is run.

You can also use a one-liner if/else statement.

main.py
my_str = 'apple' result_1 = my_str.index('z') if 'z' in my_str else None print(result_1) # 👉️ None result_2 = my_str.index('a') if 'a' in my_str else None print(result_2) # 👉️ 0

If the substring is present in the string, we return the result of calling the index() method with the substring, otherwise we return None.

Conclusion #

The Python "ValueError: substring not found" occurs when we pass a value that doesn't exist in the string to the str.index() method. To solve the error, use the find() method instead, e.g. my_str.find('z'), or handle the error using a try/except block.

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.