python - 字符串中特定字母的数量
问题描述
我正在尝试制作一个刽子手游戏(只有 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'变量中添加正确的数字
解决方案
你可以使用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)
您的代码中有什么。那是错字吗?
推荐阅读
- javascript - 应该如何声明一个空的时间戳变量,以便成为一个全局变量,以便我们稍后给它一个值?
- java - Jaxb2-maven-plugin 错误 java11 schema_reference
- amazon-web-services - 如何将 AWS 聊天机器人集成到网站中?
- c++ - 将 shared_ptr 与 CArray 一起使用?
- excel - 无限循环用文本替换空格
- angular - 禁用菜单导航项
- qt - 在 QToolTip 中设置图像时删除边距
- node.js - Update collection with $in clause mongodb
- python - 如何测试每个请求异常
- odata - 访问 SAP Cloud Platform:使用基本身份验证的 OData 供应