Search code examples
pythonstringindexoutofboundsexceptionfile-read

String index out of range exception where?


I'm trying to make a program for school which searches a text file for a string the user inputs. However I keep getting the error:

line 16, in <module>, while(test[i] != " ") IndexError: string index out of range

This is my code:

import os
myList=[]
while True:
    ans = input("Please enter a filename or 'X' to exit")
        if(ans == "X"):
        exit()
    else:
        while True:
            if os.path.exists(ans):
                with open(ans,"r") as file:
                     test = file.read()
                     print(file)
                     i=0
                     while(i <= len(test)-1):
                        sol = ""
                        while(test[i] != " "):
                            sol = sol + test[i]
                            i += 1
                        myList.append(sol)
                        i += 1
                    ans2 = input("Please enter a word to search for or 'X' to exit")
                    if(ans2 == 'X'):
                        exit()
                    else:
                        if ans2 in myList:
                            print(ans2 + " is in " + ans)
                        else:
                            print(ans2 + " is NOT in " + ans)
            else:
                print("File does not exist. Try again.")
                break

Basically it seems to me like the line while(i <= len(test)-1): should prevent the string from getting out of index so I cannot find out where I'm going out of index.


Solution

  • It seems you could greatly simplify this using for-loops. Or honestly, it looks like your nested while-loops are trying to split the string by " " character, but you could just use test.split(' ') which will return a list of strings, than you can check that list-of-strings directly