Python: Hangman TypeError: 'str' object does not support item assignment

前端 未结 1 376
栀梦
栀梦 2021-01-24 02:05

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. <

相关标签:
1条回答
  • 2021-01-24 02:47

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

    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
    
    0 讨论(0)
提交回复
热议问题