Python:Hangman TypeError:' str'对象不支持项目分配

时间:2016-01-23 18:14:41

标签: python string list

我目前正在制作一个刽子手计划,但我被困住了。每当我输入正确的猜词时,我就会一直收到错误' 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。我怎么能用输入的正确字母替换下划线?

1 个答案:

答案 0 :(得分:1)

newBoard是一个字符串,Python中的字符串是 immutable - 这就是不允许项目分配的原因。

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

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

另一种选择是使用bytearray:

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