Python ValueError: substring not found

Python ValueError: substring not found

In Python “ValueError: substring not found” error is raised when String index() method did not find the specified substring in a given string.

For example, consider the following program, where we are trying to get the index of the first occurrence of the value “banana” in the string x. The value “banana” is not present in the string x.

Python Program

x = "Some apples are red. Some apples are good."
result = x.index("banana")
print(f"Index : {result}")
Run Code Copy

Output

  File "/Users/pythonexamplesorg/workspace/main.py", line 2, in <module>
    result = x.index("banana")
             ^^^^^^^^^^^^^^^^^
ValueError: substring not found

Since the value is not present in the string, index() method raised ValueError.

Handle this ValueError

There are two ways to handle this scenario.

1. Use find() instead of index()

The first way is to use String find() method instead of String index() method. If you do not want the ValueError, then find() method does exactly that. If the substring is not found in the given string, find() method does not raise an Error, it just returns -1.

For, example, consider the following program, where we used find() method instead of index() method to find the index of first occurrence of the substring in a string.

Python Program

x = "Some apples are red. Some apples are good."
result = x.find("banana")
print(f"Index : {result}")
Run Code Copy

Output

Index : -1

The substring or value is not found in the given string x. And the find() method returns -1.

2. Use Try Except

You can use try except. Surround the call to String index() method, and handle the ValueError in the except block.

Python Program

x = "Some apples are red. Some apples are good."
try:
    result = x.index("banana")
    print(f"Index : {result}")
except ValueError:
    print("Substring not found.")
Run Code Copy

Output

Substring not found.

Summary

In this tutorial, we learned what causes “ValueError: substring not found”, and the ways to handle this ValueError, with examples.

Related Tutorials

Code copied to clipboard successfully 👍