0

I want to create a list whose size is equal to "word_len" and the default char is "_" which can be replaced later by the correct guess of the user. How can I do it? My current code:-

import random

word_list = ["aardvark", "baboon", "camel"]

chosen_word = random.choice(word_list)
word_len = len(chosen_word)

guess_letter = input("Guess a letter: ").lower()

final_list = []

for character in chosen_word:
    if character == guess_letter:
        print("Right")
    else:
        print("Wrong")
Dead Guy
  • 57
  • 1
  • 9
  • If you keep track of remaining letters in a dictionary `remaining = dict.fromkeys(chosen_word,"_")` you can remove guessed letters as you go with (`remaining.pop(guess_letter,"")` and print the result so far with `print(*(remaining.get(c,c) for c in chosen_word))`. When `remaining` is empty, the word has been found. – Alain T. Apr 17 '23 at 18:29

1 Answers1

2

_ is a display time concern. You don't need to store the displayed words with their _, you can simply generate them at display time.

To do so, you have to keep track of the letters that were guessed. Then you can check against each character of each word in word_list.

guessed = "abcd"
word_list = [ "cat", "dog", "cab" ]

print( [ ''.join([ l if l in guessed else '_' for l in word]) for word in word_list ] )
['ca_', 'd__', 'cab']

If the nested list comprehensions are making your eyes go crosseyed at first, here's an equivalent long form:

display_words = []
for word in word_list:
    new_word = ""
    for l in word:
        if l in guessed:
            new_word = new_word + l
        else :
            new_word = new_word + '_'
    display_words.append(new_word)

print(display_words)
erik258
  • 14,701
  • 2
  • 25
  • 31