Python ValueError: подстрока не найдена - ошибка определения слова

Я пытаюсь создать программу, которая при вводе предложения запрашивает слово для поиска и сообщит вам, где в предложении встречается следующий код:

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: подстрока не найдена

Я честно не знаю, как это исправить, и мне нужна помощь.


person Will King    schedule 12.01.2017    source источник
comment
заключите вызов индекса в оператор try/except ValueError.   -  person Jean-François Fabre    schedule 12.01.2017


Ответы (2)


Посмотрите, что происходит с 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.

person Steven Summers    schedule 12.01.2017

Немного отличается от вашего подхода.

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()
person Maddy    schedule 12.01.2017
comment
это было легко понять. - person Jeff Benister; 12.01.2017