Python

Valueerror: substring not found Error ( Solved )

Most of the coder use strings in their code. Suppose you want to fund the substring within a longer string. Then you use some function to find it. But if there is a mismatch in the substring then the Python interpreter raises an error Valueerror: substring not found. In this post, you will know how to solve this issue.

What causes Valueerror: substring not found Error?

The main reason for getting this error is that you are trying to find the string that is not available in the longer string. Thus raises ValueError.

You will get the Valueerror: substring not found Error when you will run the below lines of code.

string = "Data Science "
substring = "Learner"
index = string.index(substring)

Output

substring not found error

You can clearly see you are getting the error because the substring “Learner” is not present in the string “Data Science “.

Solve Valueerror: substring not found Error

Now let’s solve the substring not found Error. There can be many solutions for it. Let’s know each of them.

Solution 1: Check the substring

Before searching for the specific substring, check if the substring exists or not. It makes sure to  continue executing the other statements.

if substring in string:
   index = string.index(substring)
else:
# run the case when the substring is not found

Solution 2: Use the str.find() function

Before executing the other lines of code use the str.find() function to handle the ValueError. The function will return -1 if there is no substring in the string otherwise it will continue executing the other statements.

if substring in string:
 index = string.index(substring)
else:
 #Run the  case when the substring is not found

Solution 3: Use try-except block

The final solution is to use the try-except block. It will handle the ValueError without the need for additional conditional statements.

try:
 index = string.index(substring)
except ValueError:
 # Run the case when the substring is not found

Conclusion

You will get the Valueerror: substring not found Error when you are searching for a substring that is not available in the string. There are many solutions to it. However I suggest using the try-except to avoid additional conditional statements to handle the error.

I hope you have liked this tutorial. If you have any queries then you can contact us for more help.

Other Strings Application

Find the position of a character in String