首页 > 解决方案 > Python替换所有字符都相同的地方

问题描述

所以,我正在创建一个类似刽子手的游戏,并试图"_ _ _ _ _ _"用在正确位置猜到的角色替换一个字符串。假设这个词是"pepsi",我想替换所有"_ _ _ _ _"有 a 的地方p,如第一个和第三个_。然而,当做"_ _ _ _ _ ".replace("_", letter),这显然会将我所有的下划线替换为“p”,从而导致"p p p p p".

我的代码片段:

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!")

我应该如何从每个字符都是下划线后跟空格的字符串中替换特定的下划线?

标签: pythonreplace

解决方案


基本上,您可以迭代单词中的每个字符。然后检查您猜词中的字符是否。例如,

例 1.使用简单的循环

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

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

结果:

p _ p _  i

例 2.使用列表推导

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

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

推荐阅读