pythonfor-loopenumerate

Replacing "_" in Hangman Game with a Player Guess for All Matches


I'm getting started with coding and I tried to programm "Hangman". Now I figured most of the stuff on my own, but I'm struggling with this one. I want to save multiple indexes, so that i can replace "_" to the needed character.

guess = ""
for x in randomWord:
    guess = str(guess) + "_"

#Calculates the index for the found lette
for i in randomWord:
    wordIndex = randomWord.find(userInput)
#If Statement deconstructs string into list and adds found letter 
if wordIndex > -1:
    guess = list(guess)
    guess[wordIndex] = userInput
    guess = "".join(guess)
    missLett -= 1

I read somewhere, that enumerate could help me with my problem, but just couldn't get the hang of it.


Solution

  • Using enumerate is indeed a perfect fit for your task. It yields pairs (index, value) at each step of the iteration.

    To keep things simple, you could just iterate your randomWord a character at a time and replace the character in guess with userInput for all matching positions. Something like this should work:

    randomWord = "hippopotamus"
    guess = list("_" * len(randomWord))
    userInput = "p"
    for i, char in enumerate(randomWord):
        if char == userInput:
            guess[i] = userInput
    print("".join(guess))
    # Outputs: "__pp_p______"