2

let's say rand_word is string = 'petite' and guess is a user input of a single char

for char in rand_word:
    if char in guess:
        print(char,end='')
    else:
        print('_',end="")

in the code above if I typed the letter 'e' as my input it will output this

_e___e

My problem is how do I put this output in a variable?

3 Answers 3

1

Put your characters in a list and join it with str.join():

result = []
for char in rand_word:
    if char in guess:
        result.append(char)
    else:
        result.append('_')
result = ''.join(result)

Using a conditional expression and a list comprehension, you can put this all on one line:

result = ''.join([c if c in guess else '_' for c in rand_word])
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, I am making a hangman game using python, I had used the code you provided and It worked. But my problem is that whenever I input a letter it will output let say in 'petite' if I input the letter 'e' the output is>> e___e But when I input another letter lets say letter 't' it will output >> __t_t What I want is the first output is also included like this whenever I get a correct letter >> _e_t_te Here is my code: pastebin.com/HrV27pxT
@rccnls27: It's best if you put that in a new question; comments are not a good place to ask about new problems you encounter once your current problem is solved. You'll need to remember the previous guesses too; make a list or set guesses and add each guess letter to that, then use if char in guesses.
0

Another way to do it:

result = [char if char in guess else "_" for char in rand_word]
str_result = "".join(result)

Comments

0

Simpler, maybe

to_print = ""
for char in rand_word:
    if char in guess:
        to_print += char
    else:
        to_print += '_'
print(to_print)

The million dollar question being why might this not be a good idea...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.