0

I'm making a hangman game, recently started python and looks like a good project I'd like to do, and so far its going great, I have a function that takes a string and puts it in a list like this:

Word: duck
List: ["d", "u", "c", "k"]

Now I want to replace the D U C K letters with "_" I tried:

for char in List:
   List.replace("d", "_")

This doesn't do anything also I dont want to do it for every single letter separately I would like something like this:

for char in List:
   List.replace(char, "_")

I hope this is understandable

John Gordon
  • 29,573
  • 7
  • 33
  • 58

1 Answers1

1

You can do that in two steps:

# Find the index of the string in your list
index = List.index(char)

# Replace
List[index] = '_'

The code above would replace the first occurrence only. To replace all you can either loop while the index is not -1 or use a comprehension:

List = ['_' if c == char else c for c in List]

or if you want to replace a specified set of letters:

chars = ['D', 'U', 'C', 'K']
List = ['_' if c in chars else c for c in List]

If all you want is a series of _ characters, then you might as well use this:

List = ['_'] * len(List)
Tarik
  • 10,810
  • 2
  • 26
  • 40