【发布时间】:2017-05-27 14:31:52
【问题描述】:
我正在尝试制作一个程序,当你输入一个句子时,它会要求搜索一个词,它会告诉你句子出现在句子的哪个位置 代码如下:
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):"))
在我输入错误之前它似乎工作正常,例如你好,我的名字是 Will 我想找到的词是它而不是“对不起,这在句子中没有出现”,但实际上是 ValueError : substring not found
老实说,我不知道如何解决这个问题,需要帮助。
【问题讨论】:
-
将您的索引调用包装在
try/except ValueError语句中。
标签: python error-handling substring error-code