guanyu ma guanyu ma - 3 years ago 417
Python Question

How can I fix builtins.ValueError: substring not found

puzzle game<- this is the picture.
I get

for some inputs. Can anyone help me to fix it, please?

def update_letter_view(puzzle: str, view: str, index: int, letter: str) -> str:

>>>"""Return a single character string representing the next view of the
character at the given index.If the character at that index
of the puzzle matches the guess, then return that character. Otherwise,
return the character at that index of the view.

>>>update_letter_view('chicken', 'ch^^ken', 2, 'i')
>>>update_letter_view('banana', 'b^n^n^', 1,'t')
symbol = '^'
if letter in puzzle:
return puzzle[puzzle.index(letter, index)]
return symbol

Answer Source

Let's have a look at the python str.index() method:

str.index(str, beg=0 end=len(string))

In your function, puzzle.index(letter, index) will find the letter from the position index, so it's obvious if letter appears before index, your code will raises ValueError.

How to fix it:

def update_letter_view(puzzle, view, index, letter):
    symbol = '^'
    if letter in puzzle and puzzle.index(letter) == index:
        symbol = letter
    return symbol
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download