【问题标题】:replace character in string in python [duplicate]在python中替换字符串中的字符[重复]
【发布时间】:2018-10-22 22:56:13
【问题描述】:

我正在尝试编写一个允许用户扮演刽子手的程序。如果用户猜到某个字母,比如“p”,我想在正确的索引处替换“word”中的下划线。我不确定如何用正确猜到的字母替换下划线。感谢您的帮助!

例如

secretWord='apple'
word='_ _ _ _ _'
#user guesses 'p'
#word='_ p p _ _' (how word changes when the correct letters are guessed)

【问题讨论】:

    标签: python string python-3.x str-replace


    【解决方案1】:

    看起来你想要这样的东西:

    secret_word = 'apple'
    display_word = "_" * len(secret_word)
    guesses = 'p'
    
    new_word = ""
    for secret_char, display_char in zip(secret_word, display_word):
        if secret_char == guesses:
            new_word += secret_char
        else:
            new_word += display_char
    display_word = new_word
    
    
    print(display_word)
    

    或者作为一个列表理解(可读性受到一点影响):

    secret_word = 'apple'
    display_word = "_" * len(secret_word)
    guess = 'p'
    
    display_word = ''.join([secret_char if secret_char == guess else display_char for secret_char, display_char in zip(secret_word, display_word)])
    
    print(display_word)
    

    【讨论】:

      猜你喜欢
      • 2015-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-10
      • 2021-06-17
      • 2012-10-05
      相关资源
      最近更新 更多