pythoncharacter-replacement

How to replace the specified dash with the letter


I wish to write a hangman program and in order to do so, I have to replace the hash ('-') letter(s) with the user's guessed letter (guess). But when I run the code, it replaces all the hashes with the user's guess letter. The code seems okay but I don't get the desired result.

def word_guess():
    random.shuffle(words)
    word = words[0]
    words.pop(0)

    print(word)
    l_count = 0
    for letter in word:
        l_count += 1

    # the hidden words are shown a '-'
    blank = '-' * l_count
    print(blank)

    guess = input("please guess a letter  ")

    if guess in word:
        # a list of the position of all the specified letters in the word
        a = [i for i, letter in enumerate(word) if letter == guess]

        for num in a:
            blank_reformed = blank.replace(blank[num], guess)
            print(blank_reformed)


word_guess()

e.g: when the word is 'funny', and guess is 'n', the output is 'nnnnn'.

How should I replace the desired hash string with guess letter?


Solution

  • it replaces all the hashes

    This is exactly what blank.replace is supposed to do, though.

    What you should do is replace that single character of the string. Since strings are immutable, you can't really do this. However, lists of strings are mutable, so you could do blank = ['-'] * l_count, which would be a list of dashes, and then modify blank[num]:

    for num in a:
       blank[num] = guess
       print(blank)