简体   繁体   English

如何在 python 3.x 中用 position 替换字符串中的字母

[英]How to replace a letter in string by position in python 3.x

I am trying to create a 'hangman' game.我正在尝试创建一个“刽子手”游戏。 And for that I need to take the word the player is trying to guess, and turn all the letters they haven't yet guessed into " _ "为此,我需要将玩家试图猜测的单词,并将他们尚未猜到的所有字母变成" _ "

So let's say I have:所以假设我有:

letters_guessed = [q, r, u, a, p]
secret_word = "dragon"

How can I turn it into: _ r a _ _ _ ?我怎样才能把它变成: _ r a _ _ _

Several possible solutions here, one being:这里有几种可能的解决方案,一个是:

letters_guessed = ["q", "r", "u", "a", "p"]

secret_word = "dragon"

output = ""
for char in secret_word:
    if char in letters_guessed:
        x = char
    else:
        x = "_"
    output += x

print(output)
# Output:  _ra___

Put it in a function afterwards:之后将其放入 function 中:

def hangman(word, guessed):
    output = ""
    for char in word:
        if char in guessed:
            x = char
        else:
            x = "_"
        output += x
    return output

Alternatively, you can use a list comprehension altogether:或者,您可以完全使用列表推导:

letters_guessed = ["q", "r", "u", "a", "p"]
secret_word = "dragon"
secret_list = "".join([char if char in letters_guessed else "_" 
                       for char in list(secret_word)])
print(secret_list)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM