xupaii
xupaii

Reputation: 475

Python replace where all characters are the same

So, I'm creating a hangman-like game and am trying to replace a string like "_ _ _ _ _ _" with the character guessed in the right position. Let's say the word is "pepsi", and I want to replace all the spots in "_ _ _ _ _" where there would be a p, as in the 1st and 3rd _. However, when doing "_ _ _ _ _ ".replace("_", letter), this obviously replaces all of my underscores to "p", resulting in "p p p p p".

Snippet of my code:

while not guessed:
    word = random.choice(self.words)
    template = "_ "*len(word)
    letter = input("Guess a letter\n")
    if letter not in word: print("Incorrect")
    else:
        for x in range(len(word)):
            if word[x] == letter: 
                template.replace(template[x], letter)
    if "_" not in template: guessed = True
print(f"Guessed {word} in {10-lives} guesses!")

How should I replace a specific underscore from a string where every character is an underscore followed by a space?

Upvotes: 0

Views: 214

Answers (1)

N. Arunoprayoch
N. Arunoprayoch

Reputation: 942

Basically, you can iterate each character in a word. Then check if the character in your guessed words or not. For example,

Ex 1. Using a simple loop

word = 'pepsi'
guessed = ['p', 'i']

for s in word:
    if s in guessed:
        print(s, end='')
    else:
        print(' _ ', end='')

Result:

p _ p _  i

Ex 2. Using list comprehension

res = [s if s in guessed else '_' for s in word]

# ['p', '_', 'p', '_', 'i']

Upvotes: 3

Related Questions