我目前正在制作一个子手程序,但被卡住了。每当我为单词输入正确的猜测时,我都会不断收到错误的“ str”对象不支持项目分配。

这是我的代码:

import random

def displayBoard(randomWord):
    board = []
    for i in randomWord:
        board.append(' _ ')
    return ''.join(board)

def gameGuesses(randomWord):
    newBoard = displayBoard(randomWord)
    print(newBoard)
    mistakes = 6
    count = 0
    while not False and mistakes > 0:
       letterInput = input("\nPlease input a letter: ").upper()
       if letterInput in randomWord:
          letter = randomWord.index(letterInput)
          while count != letter:
              count += 1
              if count == letter:
                  >>>newBoard[count] = letterInput<<<#PROBLEM


       else:
           mistakes = mistakes - 1
           print("Incorrect letter.",mistakes,"remaining.")




wordList = ["Python","Hello","Random"]
randomWord = random.choice(wordList).upper()
gameGuesses(randomWord)


问题出在newBoard [count] = letterInput。我应该如何用输入的正确字母替换下划线?

最佳答案

newBoard是一个字符串,并且字符串在Python中是不可变的-这就是为什么不允许项目分配。

您必须构建一个新字符串。例如,如果要替换'helloworld'中第4位(o)处的字符,则会发出

>>> s = 'helloworld'
>>> s = s[:4] + 'X' + s[5:]
>>> s
'hellXworld'


另一种选择是使用字节数组:

>>> s = bytearray('helloworld')
>>> print(s)
helloworld
>>> s[4] = 'X'
>>> print(s)
hellXworld

10-06 01:57