首页 > 解决方案 > 再次输入时不是输出中显示的“g”吗

问题描述

输出

word = input("Enter a word: ").lower()
corrects = len(word)
players_word = "_"*len(word)
tries = 6
word_list = list(word)
for i in range(6+len(word)):
    print(players_word)
    guess = input("Enter your {} guess: ".format(i+1)).lower()
    if guess in word_list:
        corrects -= 1
        print("Correct !!!")
        players_word = list(players_word) 
        players_word[word.find(guess)] = guess
        word_list.remove(guess)
        if corrects == 0:
            print("Congratulation, you won.".title())
            breaka
    else:
        print("Wrong")
        tries -= 1
        print("You have {} tries remaining".format(tries))
        if tries == 0:
            print("Lost")
            break

一个字符出现多次的单词会发生错误。例如,在给定的图片中,“g”在再次输入时不会显示在输出中。

标签: pythonpython-3.xpython-3.9

解决方案


你的 word.find(guess) 总是会在单词中找到该字母的第一次出现。如果 word.find(guess) != "_",您需要找到一种方法来查找该字母的下一个出现。

word = input("Enter a word: ").lower()
corrects = len(word)
players_word = "_"*len(word)
tries = 6
word_list = list(word)
for i in range(6+len(word)):
    print(players_word)
    guess = input("Enter your {} guess: ".format(i+1)).lower()
    if guess in word_list:
        corrects -= 1
        print("Correct !!!")
        players_word = list(players_word)

        for i in range(len(players_word)):
            if players_word[word.replace(guess, '~', i).find(guess)] == '_':
                players_word[word.replace(guess, '~', i).find(guess)] = guess
                break

        word_list.remove(guess)
        if corrects == 0:
            print("Congratulation, you won.".title())
            break
    else:
        print("Wrong")
        tries -= 1
        print("You have {} tries remaining".format(tries))
        if tries == 0:
            print("Lost")
            break

推荐阅读