How can I print only guessed letter from a word in their corresponding indicies?

前端 未结 1 1447
無奈伤痛
無奈伤痛 2020-12-21 21:13

I am making a hangman game and I need to have to make a set of underscores that is the length of the word and when the user correctly guess a letter the corresponding space

相关标签:
1条回答
  • 2020-12-21 21:41

    You could do something like this:

    guess = "sol"
    word = "stackoverflow"
    hint = [l if l in guess else "_" for l in word]
    print "".join(hint)
    

    Here, guess is a string (or a list, or a set) holding all the letters the user has guessed so far, and word, obviously, is the word to guess. hint then is a list holding for each letter l in the word either that letter, if it is in the set of guessed letters, or an underscore. Finally, that hint is joined to a string and printed.

    Output for this example would be "s____o____lo_".

    0 讨论(0)
提交回复
热议问题