Home > Enterprise >  Substituting all letters from a string with a single character
Substituting all letters from a string with a single character

Time:10-25

I am doing an hangman game in python and I'm stuck in the part where I have a random generated word and I'm trying to hide the word by replacing all characters with dashes like this:

generated word -> 'abcd' hide word -> _ _ _ _

I have done the following:

string = 'luis'

print (string.replace ((string[i]) for i in range (0, len (string)), '_'))

And it gives me the following error:

                       ^

SyntaxError: Generator expression must be parenthesized

Please give me some types

CodePudding user response:

You could try a very simple approach, like this:

word = "luis"
print("_" * len(word))

Output would be:

>>> word = "luis"
>>> print("_" * len(word))
____
>>> word = "hi"
>>> print("_" * len(word))
__

CodePudding user response:

The simplest is:

string = "luis"

"_" * len(string)
# '____'

If you want spaces inbetween:

" ".join("_" * len(string))
# '_ _ _ _'

However, since you will need to show guessed chars later on, you are better off starting with a generator in the first place:

" ".join("_" for char in string)
# '_ _ _ _'

So that you can easily insert guessed characters:

guessed = set("eis")
" ".join(char if char in guessed else "_" for char in string)
# '_ _ i s'
  • Related