2017-01-12 14 views
2

Я пытаюсь создать программу, которая, когда вы вводите предложение, запрашивает слово для поиска, и оно сообщит вам, где в предложении это предложение возникает код выглядит следующим образом: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):")) 

это, кажется, работает хорошо, пока я типа это неправильно, например, привет, меня зовут Уилл и слово, которое я хочу найти это его вместо «извините это не происходит в предложении» но infact ValueError: substring не найден

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

+0

заверните свой индексный вызов в инструкции 'try/except ValueError'. –

ответ

0

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

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):")) 
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() 
+0

это было легко понять. –