首页 > 解决方案 > 字符串中特定字母的数量

问题描述

我正在尝试制作一个刽子手游戏(只有 6 个字母的单词),并且我正在尝试为单词中存在超过 1 个特定字母(由用户输入)时编写代码

    tries = 0
    n = 0
    word = random.choice(word_list)
    print(word)
    while  tries<10:
        guess = input("Input a letter: ")
        if guess in word:
            n = n + 1
            print("Correct. You've got,", n,"out of 6 letters.")
            if n == 6:
                print("You guessed correctly, the word was,", word)
                break
        elif word.guess(2):
            n = n + 2
            print("Correct. You've got,", n,"out of 6 letters.")
            if n == 6:
                print("You guessed correctly, the word was,", word)
                break

尽管在输入双字母进行猜测后程序继续(例如,'s' in 'across')它仍然没有在'n'变量中添加正确的数字

标签: pythonstring

解决方案


你可以使用count()它。用它来获取单词中出现的次数。如果 word 中不存在字符,则返回 0。就像在你while之后input()——

c = word.count(guess)
if c:
    n += c
    if n == 6:
        print("You guessed correctly, the word was,", word)
        break
    print("Correct. You've got,", n, " out of 6 letters.")

您可能想要检查用户输入是否确实是字符而不是字符串或''(空字符串)。这可能会混淆程序。你也没有增加tries变量。因此,用户可以无限次尝试

另外,word.guess(2)您的代码中有什么。那是错字吗?


推荐阅读