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
Traceback (most recent call last): File "<exec>", line 2, in <module> TypeError: 'str' object does not support item assignment
The fix
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.
2. Replacing characters inside a loop
This raises the error
Traceback (most recent call last): File "<exec>", line 4, in <module> TypeError: 'str' object does not support item assignment
The fix
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.
3. A line of text that you meant to use as a list
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> TypeError: 'str' object does not support item assignment
The fix
['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.
When you see this error, check
- Remember that strings cannot change: every string method returns a new string, so write
text = text.upper(), not justtext.upper(). - Use slicing to rebuild a string:
text[:i] + new + text[i + 1:]. - Use
replace()to swap text, orlist()and''.join()to edit many characters. - Print
type(value)if you expected a list and got a string.
Related errors
All Python errors · How to read a traceback · Step through your code