【问题标题】:Python ValueError: substring not found - Error defining a wordPython ValueError:找不到子字符串 - 定义单词时出错
【发布时间】: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


【解决方案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 就足够了。

【讨论】:

    【解决方案2】:

    与您的方法略有不同。

    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()
    

    【讨论】:

    • 这很容易理解。
    猜你喜欢
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    相关资源
    最近更新 更多