Меню

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

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

@vidyap-xgboost

I ran the following code on colab:

from pipelines import pipeline
nlp = pipeline("question-generation")

text = """FIO Labs is an independent, privately-owned company with a global reach.
With the agility of a startup and the ability of a conglomerate, we help
businesses understand and adopt Artificial Intelligence & Data Security
technologies in the right framework and help them stay aligned with their
strategic objectives."""

nlp(text)

and I get the following error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-23-fdf5d062d391> in <module>()
----> 1 nlp(text)

1 frames
/content/question_generation/pipelines.py in _prepare_inputs_for_qg_from_answers_hl(self, sents, answers)
    140                 answer_text = answer_text.strip()
    141 
--> 142                 ans_start_idx = sent.index(answer_text)
    143 
    144                 sent = f"{sent[:ans_start_idx]} <hl> {answer_text} <hl> {sent[ans_start_idx + len(answer_text): ]}"

ValueError: substring not found

I don’t understand why this error comes when I gave proper text.

This also occurred with

text8 = """Prashanth Bandi is one of the highly regarded consultants in the IT world, he 
is a Technology Evangelist with 18 years of consulting experience dealing with 
diverse problems and delivering technology solutions to complex business 
challenges. His adaptive nature, perseverance and genuine passion for 
technology makes him the torch bearer of our company.
"""

@patil-suraj

Hi @vidyap-xgboost , this is a known issue and I’m working on the fix, see issue #11 . Sorry for inconvenience. Will let you know when it’s fixed

@vidyap-xgboost

Thanks for the heads-up. Will look forward to the fix.

@danielmoore19

For the time being:

if answer_text in sent: ans_start_idx = sent.index(answer_text) else: continue

will allow you to bypass the ValueError by skipping mismatched answer/sent pairs. in a test, it did continue to match answer/sent pairs beyond where I was getting an error. it had been throwing an error after (3) matches, and with the if statement it completed the task with a total of (10) answer/question pairs. not a fix, but will let you process an entire, complex text.

i was using James Baldwin’s essay, If Black English Isn’t a Language, Then Tell Me, What Is?, specifically for the purpose of stress testing. you can find it here:

(https://archive.nytimes.com/www.nytimes.com/books/98/03/29/specials/baldwin-english.html?_r=1&oref=slogin)

(apologies for the code format, i couldn’t get it to break by line)

@ankitkr3

Hi @vidyap-xgboost , this is a known issue and I’m working on the fix, see issue #11 . Sorry for inconvenience. Will let you know when it’s fixed

Hi @patil-suraj is this issue fixed now ?

@danielmoore19

Hi @vidyap-xgboost , this is a known issue and I’m working on the fix, see issue #11 . Sorry for inconvenience. Will let you know when it’s fixed

Hi @patil-suraj is this issue fixed now ?

i would suggest using the if statement to work around. the issue is that sometimes the answer order gets out of place, the answer span and answer are not exact (one is Capital and the other is capital), or it actually creates an answer that does not appear the text. one of these is an issue with ordering what comes out of the I/O, one can be fixed by adding a .lower() to sent.index() and answer_text, and the last is an issue inside the model itself. thus the if statement is the only thing that will bypass all three errors. using the .lower() with the if statement will ensure you still get answers that appear in the text, but do not match in capitalization.

added — there is a more rare occurrence where an (s) gets added or dropped from the answer span.

@ronaldgevern

When you use string_object.index(substring), it looks for the occurrence of substring in the string_object. If substring is present, the method returns the index at which the substring is present, otherwise, it throws ValueError: substring not found.

Using Python’s “in” operator

The simplest and fastest way to check whether a string contains a substring or not in Python is the “in” operator . This operator returns true if the string contains the characters, otherwise, it returns false .

str="Hello, World!"
print("World" in str)//output is  True

Python “in” operator takes two arguments, one on the left and one on the right, and returns True if the left argument string is contained within the right argument string. It is important to note that the “in” operator is case sensitive i.e, it will treat the Uppercase characters and Lowercase characters differently.

The index() method returns the index of the first occurence of a substring in the given string. It is same as the find() method except that if a substring is not found, then it raises an exception.

Syntax:

str.index(substr, start, end)

Parameters:

  1. substr: (Required) The substring whose index has to be found.
  2. start: (Optional) The starting index position from where the searching should start in the string. Default is 0.
  3. end: (Optional) The ending index position untill the searching should happen. Default is end of the string.

Return Value:

An integer value indicating an index of the specified substring.

The following examples demonstrates index() method.

greet='Hello World!'
print('Index of H: ', greet.index('H'))
print('Index of e: ', greet.index('e'))
print('Index of l: ', greet.index('l'))
print('Index of World: ', greet.index('World'))

Index of H: 0
Index of e: 1
Index of l: 2
Index of World: 6

The index() method returns an index of the first occurance only.

greet='Hello World'
print('Index of l: ', greet.index('l'))
print('Index of o: ', greet.index('o'))

Index of l: 2
Index of o: 4

The index() method performs case-sensitive search. It throws ValueError if a substring not found.

greet='Hello World'
print(greet.index('h')) # throws error: substring not found 
print(greet.index('hello')) # throws error

ValueError: substring not found
ValueError: substring not found

If a given substring could not be found then it will throw an error.

mystr='TutorialsTeacher is a free online learning website'
print(mystr.index('python'))

Traceback (most recent call last)
<ipython-input-3-a72aac0824ca> in <module>
      1 str='TutorialsTeacher is a free online learning website'
----> 2 print(str.index('python'))
ValueError: substring not found

Use start and end parameter to limit the search of a substring between the specified starting and ending index.

mystr='tutorialsteacher is a free tutorials website'
print(mystr.index('tutorials',10)) # search starts from 10th index
print(mystr.index('tutorials',1, 26)) # throws error; searches between 1st and 26th index

27
ValueError: substring not found

Want to check how much you know Python?

Let me first start this off by stating that I am a complete beginner to coding and my attempts to fix this have been limited. I am trying to follow this Arduino controlled piano robot. It takes a textified midi file and uses python to translate it into 8-bit.

output_file = open("translated.txt", "w")
input_file = open("C:\Users\nby20\Downloads\megalovania.txt")
raw_input_data = input_file.read()
work_data = raw_input_data.splitlines()
result = []

#output_file = open("result.txt", "w")

def main():

    for a in work_data:
        temp_time = time_finder(a)
        
        
        if result == []:
            result.append(str(temp_time) + ",")
            if on_off_finder(a):
                result[-1] += set_bit(True, note_finder(a))
            elif not on_off_finder(a):
                result[-1] += set_bit(True, note_finder(a))
                
        elif time_finder_comm(result[-1]) == temp_time:
            result[-1] = str(temp_time) + "," + set_bit_prev(on_off_finder(a), note_finder(a), -1)

        elif time_finder_comm(result[-1]) != temp_time:
            result.append(str(temp_time) + "," + set_bit_prev(on_off_finder(a), note_finder(a), -1))

    for b in result:
        output_file.write(b)
        output_file.write("n")

    output_file.close()
            
def set_bit(On, note):
    #Takes boolean for if it is on or not, and note number.
    #Generates bit
    if(note >= 21 and note <= 28 and On):
        return str(2**(note - 21)) + ",0,0,0,0,0,0,0,0,0,0"
    elif(note >= 29 and note <= 36 and On):
        return "0," + str(2**(note - 29)) + ",0,0,0,0,0,0,0,0,0"
    elif(note >= 37 and note <= 44 and On):
        return "0,0," + str(2**(note - 37)) + ",0,0,0,0,0,0,0,0"
    elif(note >= 45 and note <= 52 and On):
        return "0,0,0," + str(2**(note - 45)) + ",0,0,0,0,0,0,0"
    elif(note >= 53 and note <= 60 and On):
        return "0,0,0,0," + str(2**(note - 53)) + ",0,0,0,0,0,0"
    elif(note >= 61 and note <= 68 and On):
        return "0,0,0,0,0," + str(2**(note - 61)) + ",0,0,0,0,0"
    elif(note >= 69 and note <= 76 and On):
        return "0,0,0,0,0,0," + str(2**(note - 69)) + ",0,0,0,0"
    elif(note >= 77 and note <= 84 and On):
        return "0,0,0,0,0,0,0," + str(2**(note - 77)) + ",0,0,0"
    elif(note >= 85 and note <= 92 and On):
        return "0,0,0,0,0,0,0,0," + str(2**(note - 85)) + ",0,0"
    elif(note >= 93 and note <= 100 and On):
        return "0,0,0,0,0,0,0,0,0," + str(2**(note - 93)) + ",0"
    elif(note >= 101 and note <= 108 and On):
        return "0,0,0,0,0,0,0,0,0,0," + str(2**(note - 101))
    else:
        return "0,0,0,0,0,0,0,0,0,0,0"

def set_bit_prev(On, note, index):
    #Same as set_bit but previous aware
    temp = result[index]
    temp = temp[(temp.find(",") + 1):]
    
    if(note >= 21 and note <= 28):
        local_temp = temp[0:temp.find(",")]
        if(On):
            return str(int(local_temp) + (2**(note - 21))) + temp[temp.find(","):]
        if(not On):
            return str(int(local_temp) - (2**(note - 21))) + temp[temp.find(","):]
        
    elif(note >= 29 and note <= 36):
        local_temp = temp[(temp.find(",") + 1):indexTh(temp, ",", 2)]
        if(On):
            return temp[0:temp.find(",") + 1] + str(int(local_temp) + (2**(note - 29))) + temp[indexTh(temp, ",", 2):]
        if(not On):
            return temp[0:temp.find(",") + 1] + str(int(local_temp) - (2**(note - 29))) + temp[indexTh(temp, ",", 2):]
        
    elif(note >= 37 and note <= 44):
        local_temp = temp[(indexTh(temp, ",", 2) + 1):indexTh(temp, ",", 3)]
        if(On):
            return temp[0:indexTh(temp, ",", 2) + 1] + str(int(local_temp) + (2**(note - 37))) + temp[indexTh(temp, ",", 3):]
        if(not On):
            return temp[0:indexTh(temp, ",", 2) + 1] + str(int(local_temp) - (2**(note - 37))) + temp[indexTh(temp, ",", 3):]
        
    elif(note >= 45 and note <= 52):
        local_temp = temp[(indexTh(temp, ",", 3) + 1):indexTh(temp, ",", 4)]
        if(On):
            return temp[0:indexTh(temp, ",", 3) + 1] + str(int(local_temp) + (2**(note - 45))) + temp[indexTh(temp, ",", 4):]
        if(not On):
            return temp[0:indexTh(temp, ",", 3) + 1] + str(int(local_temp) - (2**(note - 45))) + temp[indexTh(temp, ",", 4):]
        
    elif(note >= 53 and note <= 60):
        local_temp = temp[(indexTh(temp, ",", 4) + 1):indexTh(temp, ",", 5)]
        if(On):
            return temp[0:indexTh(temp, ",", 4) + 1] + str(int(local_temp) + (2**(note - 53))) + temp[indexTh(temp, ",", 5):]
        if(not On):
            return temp[0:indexTh(temp, ",", 4) + 1] + str(int(local_temp) - (2**(note - 53))) + temp[indexTh(temp, ",", 5):]
        
    elif(note >= 61 and note <= 68):
        local_temp = temp[(indexTh(temp, ",", 5) + 1):indexTh(temp, ",", 6)]
        if(On):
            return temp[0:indexTh(temp, ",", 5) + 1] + str(int(local_temp) + (2**(note - 61))) + temp[indexTh(temp, ",", 6):]
        if(not On):
            return temp[0:indexTh(temp, ",", 5) + 1] + str(int(local_temp) - (2**(note - 61))) + temp[indexTh(temp, ",", 6):]
        
    elif(note >= 69 and note <= 76):
        local_temp = temp[(indexTh(temp, ",", 6) + 1):indexTh(temp, ",", 7)]
        if(On):
            return temp[0:indexTh(temp, ",", 6) + 1] + str(int(local_temp) + (2**(note - 69))) + temp[indexTh(temp, ",", 7):]
        if(not On):
            return temp[0:indexTh(temp, ",", 6) + 1] + str(int(local_temp) - (2**(note - 69))) + temp[indexTh(temp, ",", 7):]
        
    elif(note >= 77 and note <= 84):
        local_temp = temp[(indexTh(temp, ",", 7) + 1):indexTh(temp, ",", 8)]
        if(On):
            return temp[0:indexTh(temp, ",", 7) + 1] + str(int(local_temp) + (2**(note - 77))) + temp[indexTh(temp, ",", 8):]
        if(not On):
            return temp[0:indexTh(temp, ",", 7) + 1] + str(int(local_temp) - (2**(note - 77))) + temp[indexTh(temp, ",", 8):]
        
    elif(note >= 85 and note <= 92):#error here
        local_temp = temp[(indexTh(temp, ",", 8) + 1):indexTh(temp, ",", 9)]
        if(On):
            return temp[0:indexTh(temp, ",", 8) + 1] + str(int(local_temp) + (2**(note - 85))) + temp[indexTh(temp, ",", 9):]
        if(not On):
            return temp[0:indexTh(temp, ",", 8) + 1] + str(int(local_temp) - (2**(note - 85))) + temp[indexTh(temp, ",", 9):]
        
    elif(note >= 93 and note <= 100):
        local_temp = temp[(indexTh(temp, ",", 9) + 1):indexTh(temp, ",", 10)]
        if(On):
            return temp[0:indexTh(temp, ",", 9) + 1] + str(int(local_temp) + (2**(note - 93))) + temp[indexTh(temp, ",", 10):]
        if(not On):
            return temp[0:indexTh(temp, ",", 9) + 1] + str(int(local_temp) - (2**(note - 93))) + temp[indexTh(temp, ",", 10):]
        
    elif(note >= 101 and note <= 108):
        local_temp = temp[(indexTh(temp, ",", 10) + 1):]
        if(On):
            return temp[0:indexTh(temp, ",", 10) + 1] + str(int(local_temp) + (2**(note - 101)))
        if(not On):
            return temp[0:indexTh(temp, ",", 10) + 1] + str(int(local_temp) - (2**(note - 101)))
        

def indexTh(in_string, find_this, th):
    #Takes String, string to find, and order to find string to find at that order
    #returns index
    order = 1
    last_index = 0
    while(True):
        temp = in_string.find(find_this, last_index)
        if(temp == -1):
            return -1
        if(order == th):
            return temp
        order += 1
        last_index = temp + 1

def time_finder(in_string):
    #Takes a string and finds time, returns it as an int
    time_end = in_string.index(" ")
    return int(in_string[0:time_end])

def time_finder_comm(in_string):
    #Takes a string and finds time, returns it as an int comma
    time_end = in_string.index(",")
    return int(in_string[0:time_end])
    
def note_finder(in_string):
    #Takes a string, looks for n=, returns n value as an int
    num_start = in_string.index("n=") + 2
    num_end = in_string.index("v=") - 1
    return int(in_string[num_start:num_end])

def on_off_finder(in_string):
    #takes a string, looks for On or Off, return true if On
    start = in_string.index(" ") + 1
    end = in_string.index("ch=") - 1
    if in_string[start:end] == "On":
        return True
    elif in_string[start:end] == "Off":
        return False

main()

This link to the textified midi file was used. before running the code I changed the input_file = open to text file path like so,

input_file = open("C:\Users\nby20\Downloads\megalovania.txt")

I am not sure if this is correct but I think it works.
After running the code I get a text output file as expected however it is blank and I get a few errors:

Traceback (most recent call last):
File "C:Usersnby20Downloadspython_code_for_translation.py", line 184, in <module>
   main()
File "C:Usersnby20Downloadspython_code_for_translation.py", line 23, in main
   result[-1] = str(temp_time) + "," + set_bit_prev(on_off_finder(a), note_finder(a), -1)
File "C:Usersnby20Downloadspython_code_for_translation.py", line 178, in on_off_finder
   end = in_string.index("ch=") - 1 
ValueError: substring not found

I found that anything except for the lines containing actual data for the notes was not readable by the code and I deleted those portions and ended up with this updated file.
After running that updated file through the code I got a similar erorr

Traceback (most recent call last):
  File "C:Usersnby20Downloadspython_code_for_translation (1).py", line 184, in <module>
    main()
  File "C:Usersnby20Downloadspython_code_for_translation (1).py", line 12, in main
    temp_time = time_finder(a)
  File "C:Usersnby20Downloadspython_code_for_translation (1).py", line 161, in time_finder
    time_end = in_string.index(" ")
ValueError: substring not found

Any suggestions on how to fix this would be greatly appreciated.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Subquery returns more than 1 row mysql ошибка
  • Su 42481 9 ошибка на пс4