python - 再次输入时不是输出中显示的“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”在再次输入时不会显示在输出中。
解决方案
你的 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
推荐阅读
- vertica - 我们在哪里可以获得 vertica DB 的资源?
- python - 如何在 Pandas 列中从反向修剪字符串
- dojo - 使用 dojo 列中的标题
- angular - 量角器 waitForAngularEnabled
- c# - App.config 格式和访问 .NET 中的数据
- ios - 如何在 Xcode 中隐藏代码文档/注释?
- java - 检查 smoothScrollToPosition 何时完成
- google-sheets - Google Sheets API:调用者没有权限
- python - Python 没有看到它在它的路径中肯定有的模块
- css - 使用 CSS 更改 Shiny titlePanel 的颜色