Python ValueError:找不到子字符串 - 定义单词时出错

时间:2017-01-12 13:02:03

标签: 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 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):"))

它似乎工作正常,直到我输入错误,例如你好我的名字是威尔 而我想要找的是它而不是"对不起,这并不会出现在句子中#34;但实际上是ValueError:未找到子字符串

老实说,我不知道如何解决这个问题并请求帮助。

3 个答案:

答案 0 :(得分:1)

查看未找到子字符串时str.indexstr.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就足够了。

答案 1 :(得分: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()

答案 2 :(得分:0)

只需将if word:更改为if word in sent:,您的代码就可以正常使用

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 in sent:
        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):"))