adam tsang adam tsang - 1 year ago 127
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

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download