ValueError: substring not found in Python [Solved]

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
3 min

banner

# 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 = 'bobby' # โ›”๏ธ ValueError: substring not found idx = my_str.index('z')

the character is not contained in the string

The str.index() method raises a ValueError if the substring is not contained in the string.

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

# Use the str.find() method to avoid getting the error

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

main.py
my_str = 'bobby' index = my_str.find('z') print(index) # ๐Ÿ‘‰๏ธ -1 if index != -1: print(my_str[index]) else: # ๐Ÿ‘‡๏ธ this runs print('The character is not contained in the string')

use str find method to avoid getting the error

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.

# Performing a case-insensitive test

If you need to call the str.index() method on a string in a case-insensitive manner, convert both strings to lowercase.

main.py
my_str = 'BOBBY' test_char = 'b' index = my_str.lower().index(test_char.lower()) print(index) # ๐Ÿ‘‰๏ธ 0

performing case insensitive test

We used the str.lower() method to convert the string and the character to lowercase to perform a case-insensitive test.

The code sample basically uses the str.index() method in a case-insensitive manner.

# Checking if the substring is contained in the string before calling index()

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

main.py
my_str = 'bobby' if 'z' in my_str: idx = my_str.index('z') print(idx) else: # ๐Ÿ‘‡๏ธ this runs print('The substring is not contained in the 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.

main.py
my_str = 'bobby' print('b' in my_str) # ๐Ÿ‘‰๏ธ True print('z' in my_str) # ๐Ÿ‘‰๏ธ 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.

# Using a try/except statement to handle the error

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 = 'bobby' try: idx = my_str.index('z') print(idx) except ValueError: # ๐Ÿ‘‡๏ธ this runs print('The substring is not contained in the string')

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

If you want to ignore the error in the except block, use a pass statement.

main.py
my_str = 'bobby' try: idx = my_str.index('z') print(idx) except ValueError: pass

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

# Using a one-liner if/else statement to get around the error

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.

# Checking if a string starts with or ends with a substring

if you need to check if a string starts with or ends with a substring, use the str.startswith() and str.endswith() methods instead.

main.py
my_str = 'bobby' test_char = 'b' if my_str.startswith(test_char): # ๐Ÿ‘‡๏ธ this runs print('The string starts with the substring') else: print('The string does not start with the substring')

The str.startswith method returns True if the string starts with the provided prefix, otherwise the method returns False.

Here is an example that uses the endswith() method.

main.py
my_str = 'bobby' test_char = 'by' if my_str.endswith(test_char): # ๐Ÿ‘‡๏ธ this runs print('The string ends with the substring') else: print('The string does not end with the substring')

The str.endswith() method returns True if the string ends with the provided suffix, otherwise the method returns False.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev