How to replace the specified dash with the letter

579 views Asked by At

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.

  • words is a list of words I have written before the function.
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?

3

There are 3 answers

0
ForceBru On BEST ANSWER

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)
1
William Bradley On

A couple things to note:

  • inefficient/un-pythonic pop operation (see this)
  • l_count is just len(word)
  • un-pythonic, unreadable replacement

Instead, here's a better implementation:

def word_guess() -> str:
    random.shuffle(words)
    word = words.pop()
    
    guess = input()

    out = ''
    for char in word:
        if char == guess:
            out.append(char)
        else:
            out.append('-')
    return out
            
0
Jamie Deith On

If you don't plan to use the locations of the correct guess later on, then you can simplify the last section of code:

word = 'hangman'
blank = '-------'
guess = 'a'

if guess in word:
    blank_reformed = ''.join(guess if word[i] == guess else blank[i] for i in range(len(word)))
    
blank_reformed
'-a---a-'

(You still have some work to do make the overall game work...)