Python ValueError:未找到子字符串-定义单词时出错
我正在尝试制作一个程序,当你输入一个句子时,它会要求你搜索一个单词,它会告诉你这个句子出现在哪里 代码如下:Python ValueError:未找到子字符串-定义单词时出错,python,error-handling,substring,error-code,Python,Error Handling,Substring,Error Code,我正在尝试制作一个程序,当你输入一个句子时,它会要求你搜索一个单词,它会告诉你这个句子出现在哪里 代码如下: loop=1 while loop: sent = str(input("Please type a sentence without punctuation:")) lows = sent.lower() word = str(input("please enter a word you would want me to locate:")) if wo
loop=1
while loop:
sent = str(input("Please type a sentence without punctuation:"))
lows = sent.lower()
word = str(input("please enter a word you would want me to locate:"))
if word:
pos = sent.index(word)
pos = pos + 1
print(word, "appears at the number:",pos,"in the sentence.")
else:
print ("this word isnt in the sentence, try again")
loop + 1
loop = int(input("Do you want to end ? (yes = 0); no = 1):"))
它似乎工作良好,直到我键入错误例如你好,我的名字是威尔
我想找到的单词是它,而不是“对不起,这句话中没有出现”,而是事实上的ValueError:substring not found
我真的不知道如何解决这个问题,需要帮助。看看
str.index
和str.find
在未找到子字符串时会发生什么
>>> help(str.find)
Help on method_descriptor:
find(...)
S.find(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
>>> help(str.index)
Help on method_descriptor:
index(...)
S.index(sub[, start[, end]]) -> int
Like S.find() but raise ValueError when the substring is not found.
对于
str.index
您需要一个try/except
语句来处理无效输入。对于str.find
if语句,检查返回值是否不是-1
就足够了。与您的方法稍有不同
def findword():
my_string = input("Enter string: ")
my_list = my_string.split(' ')
my_word = input("Enter search word: ")
for i in range(len(my_list)):
if my_word in my_list[i]:
print(my_word," found at index ", i)
break
else:
print("word not found")
def main():
while 1:
findword()
will_continue = int(input("continue yes = 0, no = 1; your value => "))
if(will_continue == 0):
findword()
else:
print("goodbye")
break;
main()
将索引调用封装在
try/except ValueError
语句中。这很容易理解。