python - 用正确的猜测字母替换下划线,Python hangman
问题描述
我正在创建一个刽子手游戏,无法用猜到的正确字母替换“_”。
我已经看到了其他答案,但仍然无法找到相关的解决方案。我无法理解:Python 刽子手,替换字母?
# some code
#vars
real_word = random_word()
secret_word = str(['_'] * len(real_word))
attempts = 999
letter = []
letters_guessed = []
# some code
# If correct guess
if letter in real_word:
# Here replace '_' with letter # IF CORRECT
预期结果:如果猜对了字母,将其替换为 secret_word 中的下划线(一个字母可以代替 1 个以上的下划线)。
解决方案
跟踪当前字母的最简单方法是使用列表。列表是可变的,因此可以轻松地在它们中间更改值。使用以下代码,它将换出匹配的字母。
real_word = "test"
secret_word = ["_"] * len(real_word)
guess = input("Guess letter: ")
# Loop through the letters in the real word
for i, letter in enumerate(real_word):
# Check if the current looped letter is equal to the guess
if letter != "_" and guess == letter:
# Set the underscore at that position to the correct letter
secret_word[i] = letter
# Output list as joined string
print("".join(secret_word))
随着猜测t
,代码将输出t__t
推荐阅读
- python - 检查 Pandas 列中是否存在元素(系列)
- google-apps-script - 在 Google 电子表格中传输和删除数据
- python - 我安装了 Pillow 并尝试使用 from PIL import Image 但它给出了错误
- javascript - 在没有 momentjs 的情况下获取长语言环境日期格式
- python - django 中不存在模板,但我有模板?
- satellite-image - 如何从光谱python库中的env文件中读取波长信息?
- css - 如何从 Next.js 中的 css 模块导入样式表?
- reactjs - 将 Foxit 的 WebPDF 引擎正确导入 React 应用程序
- angular - AWS EBS 上的 Spring Web 应用程序无法与我的 Angular 前端一起使用
- html - CSS 网格:自动放置算法的工作原理