Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading