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 created, they 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 reassign 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 actually returns a new string and leaves the original alone. Lists, dicts, and bytearray are mutable; 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"
Convert to a list, edit, and join — for many edits:
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"
Pick str.translate for bulk single-character substitutions:
table = str.maketrans("aeiou", "AEIOU") print("hello world".translate(table)) # "hEllO wOrld"
When you'd actually see this in real code
- Translating C/C++ habits:
s[i] = '\0'to null-terminate doesn't work in Python. - Trying to censor a word:
text[start:end] = "****"— needs slicing + concatenation instead. - Building a "redacted" SSN or credit-card number by overwriting positions — use slicing.
- Implementing Caesar cipher or ROT13 from scratch — use
"".join(...)with a generator.
Related errors
- TypeError: 'int' object is not subscriptable — ints don't even support reading by index, let alone writing.
- TypeError: unsupported operand type(s) for +: 'int' and 'str' — another string operation gotcha.
- 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