3

I'm trying to make a program that when you type a sentence it asks for a word to search and it will tell you where in the sentence it sentence occurs the code is as follows:

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

It seems to work fine until I type it incorrectly eg hello my name is Will and the word I want to find is it instead of "sorry this doesn't occur in the sentence" but infact ValueError : substring not found

I honestly dont know how to fix this and need help please.

1
  • wrap your index call in a try/except ValueError statement. Commented Jan 12, 2017 at 13:04

2 Answers 2

1

Have a look at what happens for str.index and str.find when substring is not found.

>>> 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.

For str.index you will need a try/except statement to handle invalid input. For str.find an if statement checking if the return value isn't -1 will suffice.

Sign up to request clarification or add additional context in comments.

Comments

1

A little different from your approach.

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

1 Comment

this was easy to understand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.