TypeError: 'str' object does not support item assignment
1 · The lesson
readWhat this error means
You tried to mutate a string in place with s[0] = "X". Strings in Python are immutable: once a string is created, it can't be changed. You can read characters by index (s[0]), but you can't overwrite them. To get a "modified" string, you build a new string and assign it to the variable.
When you see it
Traceback (most recent call last): File "main.py", line 3, in <module> word[0] = "H" TypeError: 'str' object does not support item assignment
Why it happens
Python strings are immutable for safety, hashability (so they can be dict keys), and performance (CPython can intern and cache them). Any operation that "changes" a string really returns a new string, and the original does not change. Lists, dicts, and bytearray are mutable, but strings, tuples, and bytes are not.
How to fix it
Use str.replace for character-level edits:
word = "hello" word = word.replace("h", "H", 1) # "Hello"
Slice and concatenate when you need to replace by index:
word = "hello" word = "H" + word[1:] # "Hello"
For many edits, convert to a list, edit it, and join it:
chars = list("hello") chars[0] = "H" chars[4] = "O" word = "".join(chars) # "HellO"
Use bytearray if you're really doing byte-level edits (rare in normal code, common in protocol parsing):
buf = bytearray(b"hello") buf[0] = ord("H") print(buf.decode()) # "Hello"
Use str.translate to replace many single characters at once:
table = str.maketrans("aeiou", "AEIOU") print("hello world".translate(table)) # "hEllO wOrld"
When you'd see this in real code
- Bringing habits from C/C++:
s[i] = '\0'to null-terminate doesn't work in Python. - Trying to censor a word:
text[start:end] = "****"doesn't work. Use slicing and concatenation instead. - Building a "redacted" SSN or credit-card number by overwriting positions. Use slicing instead.
- Implementing a Caesar cipher or ROT13 yourself. Use
"".join(...)with a generator.
Related errors
- TypeError: 'int' object is not subscriptable: ints don't support reading by index, so they don't support writing either.
- TypeError: unsupported operand type(s) for +: 'int' and 'str': another common mistake with strings.
- AttributeError: 'list' object has no attribute 'X': mutability confusion across types.
See Also
- All Python errors: the full index, by type and by when it happens.
- Strings (tutorial)
- String methods cheat sheet
- Immutability explained
Found this useful? Share it with a friend who’s learning Python.