我正在尝试制作一个程序,当您键入一个句子时,它会要求搜索一个词,它会告诉您它在句子中出现的位置 代码如下:
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
老实说,我不知道如何解决这个问题,需要帮助。
请您参考如下方法:
看看当找不到子字符串时 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,检查返回值是否为 -1 的 if 语句就足够了。
