Solve - ValueError: substring not found in Python

avatar

Borislav Hadzhiev

Sun Apr 24 20222 min read

Solve - 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 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 ran.

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.

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