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

4
  • 3
    List = ["_" for character in List] Commented Jan 18, 2021 at 3:06
  • Also, lists don't have a .replace() method, so I don't see how your code could have run. Commented Jan 18, 2021 at 3:07
  • @JohnGordon That will replace everything by _ Commented Jan 18, 2021 at 3:09
  • @Tarik The questioner said: Now I want to replace the D U C K letters with "_" Commented Jan 18, 2021 at 3:11

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.