gpt4 book ai didi

Python hangman,替换字母?

转载 作者:行者123 更新时间:2023-11-28 21:53:16 24 4
gpt4 key购买 nike

如何让我的 python hangman 游戏将变量 blanks 中的下划线替换为正确的字母(如果猜到的话)。

我有正确的 if 语句,但我不确定如何替换字母。

这是我尝试过的:

def main()
if choice in correctAnswer:
print("\nCorrect!\n------...\n")

index = 0
while index < len(correctAnswer):
index = correctAnswer.find(choice, index)
if index == -1:
break
print(index)
index += 1

used.append(choice)

places = []
place=correctAnswer.index(choice)
blanks[place]=choice
blanks=''.join(blanks)
main()

这给了我 typeError: TypeError: 'str' object does not support item assignment

关于如何做到这一点有什么想法吗?

谢谢

更新:

blanks = list(makeBoard(correctAnswer))

print (correctAnswer)

def main():
used = []
print(blanks)
choice = input("\nEnter a letter:")

if len(choice) == 1 and special_match(choice) == True:

if choice in correctAnswer:
print("\nCorrect!\n--------------------------------------------------------------------\n")

index = 0
while index < len(correctAnswer):
index = correctAnswer.find(choice, index)
if index == -1:
break
print(index)
index += 1

used.append(choice)

[choice if letter == choice else blank for blank, letter in zip(blanks, correctAnswer)]

main()

最佳答案

你最好使用列表,因为字符串是不可变的

>>> blanks = list('_______')
>>> answer = 'hangman'
>>> guess = 'g'

>>> blanks[answer.index(guess)] = guess
>>> blanks
['_', '_', '_', 'g', '_', '_', '_']

所以这使 blanks 可变,因此您可以随意替换元素。然后当你想把它作为一个字符串显示给用户时

>>> ''.join(blanks)
'___g___'

列表理解可以处理重复的字母

>>> [guess if letter == guess else blank for blank, letter in zip(blanks, answer)]
['_', 'a', '_', '_', '_', 'a', '_']

编辑
请看下面的快速演示,注意你应该添加对错误猜测的处理

answer = 'hangman'
blanks = list('_'*len(answer))
for guess in set('hangman'):
blanks = [guess if letter == guess else blank for blank, letter in zip(blanks, answer)]
print(''.join(blanks))

输出

h______
h__g___
h__gm__
ha_gma_
hangman

关于Python hangman,替换字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26937153/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com