Python:Hangman TypeError:'str'对象不支持项目分配 [英] Python: Hangman TypeError: 'str' object does not support item assignment

查看:88
本文介绍了Python:Hangman TypeError:'str'对象不支持项目分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently making a hangman program but I am stuck. Whenever I enter a correct guess for the word I keep getting the error 'str' object does not support item assignment.

这是我的代码:

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.我应该如何用输入的正确字母替换下划线?

The problem is at newBoard[count] = letterInput. How am I supposed to replace the underscore with the correct letter inputted?

推荐答案

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

newBoard is a string and strings are immutable in Python - that's why item assignment is not allowed.

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

You must build a new string. For example, if you wanted to replace the character at position 4 (the o) in 'helloworld', you'd issue

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

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

Another option would be to use a bytearray:

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

这篇关于Python:Hangman TypeError:'str'对象不支持项目分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆