Substring not found python ошибка

def get_file():
  lst_Filename = []
  while True:
    Filename = input('\nPlease enter name of ballot file: ')
    try:    
        read_Filename = open(Filename, 'r')
        txt_Filename = read_Filename.readlines()
        lst_Filename = [word.strip() for word in txt_Filename]
        read_Filename.close()
        return lst_Filename
    except IOError:
        print("The file",Filename,"does not exist.")
        continue


lst_Filename = get_file()
lst2 = {}
for item in lst_Filename:
    if item.index('1') == 0:
        print(item)

The lst_Filename is structured as follows: [‘1490 2 Mo’, ‘1267 3 Mo’, ‘2239 6 Mo’, ‘1449 7 Ks’], the actual file contains hundreds of items in the list.

I am trying to select the item that begins with ‘1’. When I run the program, the first two items is printed

1490 2 Mo

1267 3 Mo

then I get the ValueError: substring not found, it says the problem is with the line «if item.index(‘1’) == 0:», i assume because ‘2239 6 Mo’ does not begin with ‘1’

What I don’t understand is that my codes says for every item in the lst_Filename, if that item(which is a string) has the substring ‘1’ in its 0 index then select the item.

Isn’t the ‘if’ a selection statement, why doesn’t the program skips through items that don’t begin with ‘1’.

def get_file():
  lst_Filename = []
  while True:
    Filename = input('\nPlease enter name of ballot file: ')
    try:    
        read_Filename = open(Filename, 'r')
        txt_Filename = read_Filename.readlines()
        lst_Filename = [word.strip() for word in txt_Filename]
        read_Filename.close()
        return lst_Filename
    except IOError:
        print("The file",Filename,"does not exist.")
        continue


lst_Filename = get_file()
lst2 = {}
for item in lst_Filename:
    if item.index('1') == 0:
        print(item)

The lst_Filename is structured as follows: [‘1490 2 Mo’, ‘1267 3 Mo’, ‘2239 6 Mo’, ‘1449 7 Ks’], the actual file contains hundreds of items in the list.

I am trying to select the item that begins with ‘1’. When I run the program, the first two items is printed

1490 2 Mo

1267 3 Mo

then I get the ValueError: substring not found, it says the problem is with the line «if item.index(‘1’) == 0:», i assume because ‘2239 6 Mo’ does not begin with ‘1’

What I don’t understand is that my codes says for every item in the lst_Filename, if that item(which is a string) has the substring ‘1’ in its 0 index then select the item.

Isn’t the ‘if’ a selection statement, why doesn’t the program skips through items that don’t begin with ‘1’.

There are two efficient ways to fix the “ValueError: substring not found” error in Python: using the startswith() and the find() function. The following article will describe the solutions in detail.

What causes the ValueError: substring not found in Python?

The ValueError: substring not found happens because you use the index function to find a value that doesn’t exist.

Example

myString = 'visit learnshareit website'

# Use the index function
print(myString.index('wel'))

Output:

Traceback (most recent call last):
  File "code.py", line 4, in <module>
    print(myString.index('wel'))
ValueError: substring not found

How to solve this error?

Use the startswith() function

Using the startswith() function is also a good solution for you to solve this problem.

Syntax:

str.startswith(str, begin=0,end=len(string))

Parameters:

  • str: The string you provided wants to check.
  • begin: The parameter is not required. Specify the location to start the search.
  • end: The parameter is not required. Specify the location to end the search.

The startswith() function determines whether the substring occurs in an original string that you provide. If the substring is present, it will return True. And when the substring is not present, it will return False.

Example:

  • Create a string.
  • Illustrate the use of startswith() function with appear and non-appearance substrings.
myString = 'visit learnshareit website'

# Performs a search for a value that is not in the string
result1 = myString.startswith("wel")

print('Return value when substring is not present:', result1)

# Performs a search for a value that is in the string
result2 = myString.startswith("visit")

print('Return value when substring appears:', result2)

Output:

Return value when substring is not present: False
Return value when substring appears: True

The substring ‘wel’ does not appear in the original string, and the function returns False.

The substring ‘visit’ appears in the original string, and the function returns True.

Use the find() function

Using the find() function is the best way to replace the index function to avoid the exception.

Syntax:

str.find(str, beg=0 end=len(string))

Parameters:

  • str: The string you provided wants to check.
  • begin: Specify the starting index. The default index is 0.
  • end: Specify the end index. The default index is the string length (use the len() function to determine).

The find() function determines whether the substring appears in the original string. If a substring occurs, the function returns the index, otherwise it returns -1.

Note: the find() function is better than the index function in that it doesn’t throw an exception that crashes the program.

Example:

Create a string.

Illustrate the use of startswith() function with appear and non-appearance substrings.

myString = 'visit learnshareit website'

# Performs a search for a value that is not in the string
result1 = myString.find("wel")

print('Return value when substring is not present:', result1)

# Performs a search for a value that is in the string
result2 = myString.find("visit")

print('Return value when substring appears:', result2)

Output:

Return value when substring is not present: -1
Return value when substring appears: 0

Substring does not appear function returns -1.

The substring appears with an index of 0.

Summary

Those are the two ways I recommend you to fix the ValueError: substring not found in Python. If you want to return a Boolean value, use the startswith() function, and if you want to return an index value, use the find() function depending on your search purpose. Good luck!

Maybe you are interested:

  • ValueError: I/O operation on closed file in Python
  • ValueError: object too deep for desired array
  • ValueError: min() arg is an empty sequence in Python

Jason Wilson

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.


Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java

Last updated on 

Often programmers with different background are confused by error:

ValueError: substring not found

when they are trying to find character in a string like:

mystring = 'This is a simple string test].'
begin = mystring.index('[')

The behavior is not expected by many programmers to have an error for this search. A more expected behavior is to get -1 or not found instead of error. This can be done by using method find():

mystring = 'This is a simple string test].'
begin = mystring.find('[')
print(begin)

result:

-1

Behavior of the functions is the same if a substring is found.

Another difference of the two functions is that index is available for lists, tuples while found is only for strings.

In Python, the ValueError: substring not found error occurs when you try to find a substring in a string using the index() function, but the substring is not present in the string. In this tutorial, we’ll a deeper look at this error and understand why this error occurs and how can we fix it.

fix valueerror substring not found in python

Understanding the ValueError: substring not found error

The most common scenario in which this error occurs is when you’re trying to find the index of a substring inside a string using the built-in string index() function. If the substring is not present in the string, this error is raised.

Let’s take a look at the index() function.

The index() function in Python is used to find the index of the first occurrence of a substring in a given string. It returns the index of the first character of the substring if it is found in the string, otherwise, it raises a ValueError exception.

# create a string
string = "Peter Parker"
# index of the string "Parker"
index = string.index("Parker")
print(index)

Output:

6

In the above example, the index() function is used to find the index of the first occurrence of the substring “Parker” in the string “Peter Parker”. The function returns the value 6, which is the starting index of the first occurrence of the substring “Parker” in the string.

If you try to find the index of a substring not present in the string using the index() function, you’ll get an error.

# create a string
string = "Peter Parker"
# index of the string "Venom"
index = string.index("Venom")
print(index)

Output:

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

Cell In[5], line 4
      2 string = "Peter Parker"
      3 # index of the string "Venom"
----> 4 index = string.index("Venom")
      5 print(index)

ValueError: substring not found

In the above example, we try to find the index of the substring “Venom” in the string “Peter Parter”. Since this substring is not present in the given string, we get a `ValueError: substring not found” error.

How to fix the error?

Now that we know why this error occurs, let’s look at some ways in which we can resolve this error –

  1. Using the string find() function
  2. Using exception handling

Using the string find() function

The find() function in Python is a built-in string method that also returns the index of the first occurrence of a substring within a string but instead of giving an error if the substring is not present, it returns -1.

Let’s look at an example.

# create a string
string = "Peter Parker"
# index of the string "Venom"
index = string.find("Venom")
if index != -1:
    print("Substring found at index: ", index)
else:
    print("Substring not present")

Output:

Substring not present

In the above example, we are using the find() function to get the index of the substring “Venom” inside the string “Peter Parker”. You can see that we don’t get an error here.

Using exception handling

Alternatively, you can also use exception handling to tackle this error. Put the code where you’re trying to find the index of the substring using the index() function inside a try block and catch any ValueError that may occur.

Let’s look at an example.

# create a string
string = "Peter Parker"
# index of the string "Venom"
try:
    index = string.index("Venom")
    print("Substring found at index: ", index)
except ValueError:
    print("Substring not found")

Output:

Substring not found

We don’t get an error here because we’re catching the ValueError if it occurs and then printing out a message stating the substring was not found.

Conclusion

The ValueError: substring not found error occurs when you try to find a substring in a string using the string index() function, but the substring is not present in the string. To fix this error, you can use the string find() function instead that returns -1 if a substring is not present instead of raising an error. You can also use a try-except block to handle the error.

You might also be interested in –

  • How to Fix – TypeError ‘int’ object is not subscriptable
  • How to Fix – ValueError: could not convert string to float
  • How to Fix – TypeError: can only concatenate str (not ‘int’) to str
  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts

Понравилась статья? Поделить с друзьями:
  • Substance painter ошибка драйвера
  • Subaru ошибка p0154
  • Subquery returns more than 1 row mysql ошибка
  • Subaru ошибка c0140
  • Subsistence ошибка 0xc000007b