我正在尝试为学校制作一个程序,该程序在文本文件中搜索用户输入的字符串。但是我一直收到错误:
line 16, in <module>, while(test[i] != " ")
IndexError: string index out of range
这是我的代码:
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
基本上在我看来,行while(i <= len(test)-1):
应该阻止字符串脱离索引,所以我无法找到我退出索引的位置。
答案 0 :(得分:0)
似乎你可以使用for循环大大简化这一点。或者老实说,看起来你的嵌套while循环试图将字符串拆分为&#34; &#34;字符,但你可以使用test.split(' ')
返回一个字符串列表,而不是直接检查字符串列表