adam tsang adam tsang - 8 months ago 51
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)
splitlist = list(guessWord)
dash = "_ " * len(splitlist)
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


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)