adam tsang adam tsang - 1 month ago 11
Python Question

A ""'str' object does not support item assignment"" when replacing elements in a list

hi guys unsure what is wrong. This is the start of my code of hangman but I get an error...

Traceback (most recent call last):

File "python", line 14, in module

TypeError: 'str' object does not support item assignment

import random
listOfWords = ["example", "potato", "python", "rocks","test", "hangman"]
guessWord = random.choice(listOfWords)
print(guessWord)
splitlist = list(guessWord)
print(splitlist)
dash = "_ " * len(splitlist)
print(dash)
while 0 == 0:
guess = input("Guess a letter: ")
if guess in guessWord:
for n,i in enumerate(splitlist):
if i == guess:
dash[n] = guess


any help would be greatly appreciated thanks

Answer

The line:

dash = "_ " * len(splitlist)

will give you a string which will be immutable. Not sure if you need a list instead of string:

dash = ["_"] * len(splitlist)