PythonMastery
reference 3 min read · lesson 10 of 60 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 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

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

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"

For many edits, convert to a list, edit it, and join it:

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"

Use str.translate to replace many single characters at once:

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

See Also

Found this useful? Share it with a friend who’s learning Python.