+2 votes
in Programming Languages by (17.0k points)
reshown by

I have a list variable with initial value '_____'. I want to replace all '_' with some numbers, but I am getting the following error: TypeError: 'str' object does not support item assignment.

Here is my code.

>>> t


>>> t[1]=2

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: 'str' object does not support item assignment

1 Answer

0 votes
by (29.1k points)

Your variable 't' is a string, so you cannot alter its characters like the way you are doing. You can declare the variable 't' as a list and then you can change its elements.

Here is an example:

>>> t=['_']*5
>>> t
['_', '_', '_', '_', '_']
>>> t[3]=12
>>> t
['_', '_', '_', 12, '_']