替换某些指数的字母

时间:2017-11-14 18:24:12

标签: python string

我目前正在制作一个刽子手计划。它开始并要求你写一封信,然后如果你做对了,它会用字母取代那个字的短划线。

例如:

如果这个词是爵士乐,并且你选择了a,它就会出现

-a--

现在当你猜测一个z时,它应该是

-azz

但相反,它仅在字母z出现的第一个索引处打印z。

-az- 

到目前为止,这是我的代码:

secret_word = "jazz"
dashes = "----"


def get_guess():
    while True:
        print dashes
        guess = input("Guess: ")
        if len(guess) > 1:
            print "Your guess must have exactly one character!"
        elif guess.isupper():
            print "Your guess must be a lowercase letter!"
        elif guess.isdigit():
            print "Your guess must be a letter!"
        else:
            return guess
            break


def update_dashes(secret_word, dashes, guess):
    for i in range(len(secret_word)):
        if guess == secret_word[i]:
            #right here is where I change the dashes to letters.
            dashes = dashes[:i] + guess + dashes[i + 1:]
            return dashes




while True:
    user_guess = get_guess()
    dashes = update_dashes(secret_word, dashes, user_guess)
    if user_guess in secret_word:
        print "That letter is in the secret word!"
    else:
        print "That letter is not in the secret word!"

2 个答案:

答案 0 :(得分:3)

您在return dashes循环内部for 执行if {在for循环中的if内部。这意味着从for“触发”的那一刻开始,您将返回结果。

您应该在def update_dashes(secret_word, dashes, guess): for i in range(len(secret_word)): if guess == secret_word[i]: dashes = dashes[:i] + guess + dashes[i + 1:] return dashes # for loop ended, all possible replacements done循环之后返回

zip

更多Pythonic版本可能与str.join一起使用(并使用def update_dashes(secret_word, dashes, guess): return ''.join(guess if guess == real else old for real, old in zip(secret_word, dashes))):

secret_word

这里我们在dashessecret_word上并行迭代。如果realguess)的字符等于guess,则会发出old,否则我们会发出this字符。然后我们将所有这些字符连接在一起。

答案 1 :(得分:2)

indentation update_dashes中出现function个错误。您希望循环遍历secret_word的整个长度,反复替换characters,并且仅在完成后return dashes string

def update_dashes(secret_word, dashes, guess):
    for i in range(len(secret_word)):
        if guess == secret_word[i]:
            #right here is where I change the dashes to letters.
            dashes = dashes[:i] + guess + dashes[i + 1:]
    return dashes

interpreter

中只有一点测试
>>> update_dashes("bob", "---", "b")
'b-b'

看起来很棒!的:)