Editor

TypeError: 'str' object does not support item assignment

What it means

You tried to change one character of a string with text[i] = .... Strings in Python are immutable: once made, they cannot be changed in place. You build a new string instead and assign it back to the variable.

1. Changing one character by its position

This raises the error

Broken
name = 'python'
name[0] = 'P'
print(name)
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
TypeError: 'str' object does not support item assignment

The fix

Fixed
name = 'python'
name = 'P' + name[1:] # build a new string
print(name)
Output
Python

name[1:] is everything after the first character, so joining it to 'P' makes a new string. For this exact job, name.capitalize() does it in one step.

Try fixing it yourself in the editor

2. Replacing characters inside a loop

This raises the error

Broken
word = 'banana'
for i in range(len(word)):
if word[i] == 'a':
word[i] = '*'
print(word)
Output
Traceback (most recent call last):
  File "<exec>", line 4, in <module>
TypeError: 'str' object does not support item assignment

The fix

Fixed
word = 'banana'
letters = list(word) # a list can be changed
for i in range(len(letters)):
if letters[i] == 'a':
letters[i] = '*'
word = ''.join(letters)
print(word)
print('banana'.replace('a', '*')) # the one-line way
Output
b*n*n*
b*n*n*

A list of characters can be changed item by item, and ''.join() turns it back into a string. When you are swapping one piece of text for another, replace() is simpler.

Try fixing it yourself in the editor

3. A line of text that you meant to use as a list

This raises the error

Broken
row = 'Ana,31,London'
row[2] = 'Paris'
print(row)
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
TypeError: 'str' object does not support item assignment

The fix

Fixed
row = 'Ana,31,London'
fields = row.split(',') # ['Ana', '31', 'London']
fields[2] = 'Paris'
print(fields)
print(','.join(fields))
Output
['Ana', '31', 'Paris']
Ana,31,Paris

A line from a file or a CSV is one string, not a list. split(',') turns it into a list you can change, and ','.join() turns it back.

Try fixing it yourself in the editor

When you see this error, check

  • Remember that strings cannot change: every string method returns a new string, so write text = text.upper(), not just text.upper().
  • Use slicing to rebuild a string: text[:i] + new + text[i + 1:].
  • Use replace() to swap text, or list() and ''.join() to edit many characters.
  • Print type(value) if you expected a list and got a string.

All Python errors · How to read a traceback · Step through your code