【问题标题】:Python replace where all characters are the samePython替换所有字符都相同的地方
【发布时间】: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 检查我的编辑

标签: python replace


【解决方案1】:

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

Ex 1.使用简单的循环

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

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

结果:

p _ p _  i

Ex 2.使用列表推导

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

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

【讨论】:

  • 有没有办法让我当前的代码可以工作?这两种方法与我目前的方法截然不同
  • 另外,当我猜到字母e时,这不起作用,p将替换为_,导致"_ e _ _ _"
  • @xupaii 如果您将猜到的单词以列表的形式保存,则效果很好:guessed = ['p', 'e']
  • 哦,真是天才!!谢谢哈哈
  • @xupaii 希望我的回答对您有所帮助。无论如何,这只是一个想法。不要忘记考虑用户输入的大小写字母,以及猜测单词的重复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-18
  • 1970-01-01
  • 2016-09-26
  • 2021-06-08
  • 2010-09-22
相关资源
最近更新 更多