'Python Hangman problem with function for printing "_ a _ _ e _"

I am programming a small hangman game and I have kinda no Idea how I should resume my program. I have the part of the program which is giving me a list of the letters which are guessed correctly. My problem is that I don't know how to write the part where if I have a list with the known letters = [a, e] and the word "Banner", that it prints me a good user output which is using known letters and the word. Something like that: (known_letters and the word): "_ a _ _ e _". Do you have any ideas on how I can write this function efficiently? Thank you for your answers (:

word = "Banner"
known_letters = ["a", "e"]
def print__(word, letter):
  print(word, letter)
  for letters in word:
    if letter in word:
      #I have no Idea how to resume ):
#Output should be something like _ a _ _ e r.


Solution 1:[1]

You have some of the parts you need already there, a for-loop and some condition checking if a letter is in the word.

Here's a nice way to put that together:

word = "Banner"
known_letters = ["a", "e"]
to_print = ''.join(letter if letter in known_letters else '_' for letter in word)
print(to_print)

Or if you want spaces inbetween:

to_print = ' '.join(letter if letter in known_letters else '_' for letter in word)

These work because str.join() takes some iterable of strings and joins them together with the string it is called on, i.e. '-'.join('a', 'b', 'c') returns 'a-b-c'.

And letter if letter in known_letters else '_' evaluates to the value of letter if letter is in known_letters and it evaluates to '_' otherwise.

So, doing that for all letters in word, gets you all the characters which can then be joined together (with empty strings, or spaces).

Solution 2:[2]

word = "Banner"
known_letters = ["a", "e"]
def print__(word, letter):
    print(word, letter)
    answer=""
    for letters in word:
        if letters in known_letters:
            answer+=letters+" "
        else:
            answer+="_ "
    return answer
  
x=print__(word,known_letters)
print(x)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Grismar
Solution 2 leoz