Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ValueError: substring not found - Error defining a word

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.

like image 383
Will King Avatar asked Dec 05 '25 10:12

Will King


1 Answers

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.

like image 125
Steven Summers Avatar answered Dec 07 '25 00:12

Steven Summers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!