python - 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!")
我应该如何从每个字符都是下划线后跟空格的字符串中替换特定的下划线?
解决方案
基本上,您可以迭代单词中的每个字符。然后检查您猜词中的字符是否。例如,
例 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']
推荐阅读
- html - Bootstrap 3 align-items-end 等价
- php - MySQLi 多表查询
- reactjs - History.Push 影响所有选项卡而不是当前选项卡
- unity3d - 如何优化 2D 游戏统一性(EarlyUpdate.PlayerCleanupCacheData)?
- amcharts - AM Charts - 以正确数据显示的折线图
- julia - 没有方法匹配错误,但识别匹配方法
- html - 在一行中使用完整的列高
- react-native - 如何使视图高度根据其兄弟姐妹的连续高度展开?
- java - 为什么我需要创建一个 Kafka Consumer 来连接到 Schema Registry?
- android - 无法生成签名的apk,kotlin