The hangman code that I am referencing comes from the Invent Your Own Games with Python book:
In the function that displays the game board, there is a for loop that replaces a string composed of underscores with the correct, guessed letters corresponding to whatever the secretWord is:
for i in range(len(secretWord)):
if secretWord[i] in correctLetters:
blanks = blanks[:i] + secretWord[i] + blanks[i+1]
I have trouble trying to understand and visualize the line blanks = blanks[:i] + secretWord[i] + blanks[i+1]
Let's say secretWord = "otter"
and blanks = "_____"
(five underscores). How exactly would the for loop work?
Let's imagine you got the letter 't' correct. So correctLetters=['t'] and we go through our secret word, to see where the t appears.
For i = 0 nothing happens, 'o' is not in our correctLetters.
For i = 1 we got the 't', it's part of correctLetters, so we are able to do the magic with the blanks:
| blanks[:i] gets the String until position i=1, so here: '_'
secretWord[i] gives you the 't', as i=1
blanks[i+1] gives you all the rest of the string, starting from position i+1=2 -> ___
Overall you have _t___ after this iteration.
You'll we do the same again with another t (i=2 now) and you'll have: blanks = _tt__
And then it's super easy to guess Otter, right ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With