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’.

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

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

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

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

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

Python ValueError: substring not found

ValueError: substring not found

Python raises ValueError: substring not found when the index() function fails to find a given substring.

Let’s look at an example case. The code below runs a for loop over a word list, trying to locate each word inside the given quote:

quote = "I knew exactly what to do, but in a much more real sense I had no idea what to do."
word_list = ["real", "idea", "jamrock"]

for word in word_list:
    i = quote.index(word)
    print(f"{i} - {word}")

Out:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[2], line 5
      2 word_list = ["real", "idea", "jamrock"]
      4 for word in word_list:
----> 5     i = quote.index(word)
      6     print(f"{i} - {word}")
ValueError: substring not found

The for loop fails at its third run because index() cannot find 'jamrock' in quote.

When we use index() to locate substrings in whose existence we are not confident, we risk termination. We should reinforce our code against the error or replace the index() call completely.

This article will discuss several solutions and their possible advantages over one another.

On String values, the function find() works almost identically to index() with one crucial difference — when find() fails, instead of raising an error, it returns -1.

Let’s bring back the example from the intro and swap the index() for find():

quote = "I knew exactly what to do, but in a much more real sense I had no idea what to do."
word_list = ["real", "idea", "jamrock"]

for word in word_list:
    i = quote.find(word)
    print(f"{i} - {word}")

Out:

46 - real
66 - idea
-1 - jamrock

Like index(), find() also takes the optional start and end parameters. So if we wanted to narrow the search between two indexes, we could still do it.

Below, the second find() call uses the index where the first 'word' ends and the quote’s length to bracket the search:

quote = "Me think, why waste time say lot word, when few word do trick."

first_occurrence = quote.find("word")
second_occurrence = quote.find("word", first_occurrence + 4, len(quote))

print(first_occurrence, second_occurrence)

Though find() seems like the perfect substitute for index(), there is a subtle difference: while index() is available for lists and tuples, find() only applies to string values.

It’s also important to note that -1 is a valid index marking the last element of a sequence. This can cause problems when using the fetched indexes in further processing.

You can see a simple demonstration of the pitfall below:

s = "abcdef"
i = s.find("k")  # returns -1, since there is no 'k'

print(s[i])

This issue, however, can easily be resolved by a conditional statement:

s = "abcdef"
i = s.find("k")  # returns -1, since there is no 'k'

print(s[i] if i > -1 else "###")

One way of working around a possible ValueError is wrapping the index() call in a try-except block, like so:

quote = "Should have burned this place down when I had the chance."
word_list = ["when", "jamrock", "burn"]

for word in word_list:
    try:
        i = quote.index(word)
    except ValueError:
        print(f"Couldn't find the word: '{word}'.")
        i = "#"
    print(f"{i} - {word}")

Out:

35 - when
Couldn't find the word: 'jamrock'.
# - jamrock
12 - burn

This option takes a bit more typing but allows us to assign a fallback index or print a custom message when index() fails.

One other solution is to ensure the existence of the substring using if...in before calling index(), like so:

quote = "I have to be liked. But it’s not like this compulsive need like my need to be praised."
word_list = ["praise", "like", "jamrock"]

for word in word_list:
    if word in quote:
        i = quote.index(word)
    else:
        i = "#"
    print(f"{i} - {word}")

Out:

78 - praise
13 - like
# - jamrock

One advantage this method has over the try-except option is that we can compress the if-else block into one line like this:

for word in word_list:
    i = quote.index(word) if word in quote else "#"
    print(f"{i} - {word}")

Out:

78 - praise
13 - like
# - jamrock

The downside is that if...in impacts performance when used over many iterations due to the extra lookup to check if the substring exists. Refer to the previous solution if this performance hit is a concern.

When index() function fails to find a given substring within a string, it raises the ValueError: substring not found.

To prevent the program from crashing, we can replace the index() method with find(), which performs the same string operation yet fails in silence. It is also helpful to wrap the index() call in a try-except block or to use if-in to check the existence of the substring before calling index().

Last updated on 
Feb 10, 2022

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.

Понравилась статья? Поделить с друзьями:
  • Subscript out of range vba excel ошибка
  • Subscript out of bounds ошибка
  • Subquery returns more than 1 row mysql ошибка
  • Subquery returned more than 1 value ошибка
  • Streamlabs obs ошибка при выводе