+2 votes
in Programming Languages by (73.8k 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

+1 vote
by (349k points)
selected by
 
Best answer

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, '_']
>>>


...