PythonMastery
reference 3 min read · lesson 10 of 45 in Errors

TypeError: 'str' object does not support item assignment

1 · The lesson

read

What 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

python
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:

python
word = "hello"
word = word.replace("h", "H", 1)        # "Hello"

Slice and concatenate when you need to replace by index:

python
word = "hello"
word = "H" + word[1:]                   # "Hello"

Convert to a list, edit, and join — for many edits:

python
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):

python
buf = bytearray(b"hello")
buf[0] = ord("H")
print(buf.decode())                     # "Hello"

Pick str.translate for bulk single-character substitutions:

python
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.

See Also