【发布时间】:2019-08-29 09:51:44
【问题描述】:
所以,我正在创建一个类似刽子手的游戏,并尝试将"_ _ _ _ _ _" 之类的字符串替换为在正确位置猜到的角色。假设这个词是"pepsi",我想替换"_ _ _ _ _" 中存在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!")
我应该如何从每个字符都是下划线后跟空格的字符串中替换特定下划线?
【问题讨论】:
-
请分享您现有的代码。
-
@Selcuk 检查我的编辑