Skip to content

/errors/python/typeerror-str-object-does-not-support-item-assignment

TypeError: 'str' object does not support item assignment

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · Python 3.13.15updated
tool
Python
exit code
1
versions
Python 3.x
os
any

TypeError: 'str' object does not support item assignment means the code tried to change a character of a string in place, like s[0] = "J". Python strings are immutable. Create a new string instead and bind it to the same name.

Reproduce it

bash
cat > app.py <<'EOF'
s = "hello"
s[0] = "J"
EOF
python app.py

Output · exit 1

Traceback (most recent call last):
  File "/tmp/work/app.py", line 2, in <module>
    s[0] = "J"
    ~^^^
TypeError: 'str' object does not support item assignment

Fixes

bash
cat > fix.py <<'EOF'
s = "hello"
print("J" + s[1:])            # slicing
print(s.replace("h", "J"))    # replace known text
chars = list(s)               # list of characters
chars[0] = "J"
print("".join(chars))
b = bytearray(b"hello")       # mutable bytes
b[0] = ord("J")
print(b.decode())
EOF
python fix.py

Output

Jello
Jello
Jello
Jello

Each fix returns a new object; the original s is unchanged. If the variable should have been a list, check where it was created: input() and str.split() results, and values read from JSON or a file, are often strings.

What the message means

A Python str is an immutable sequence: once created, its characters cannot change. Indexing (s[0]) and slicing (s[1:3]) read from it, but writing to an index or a slice is not supported. Deleting a character fails with a related message, and other immutable types report the same error with their own name:

bash
cat > forms.py <<'EOF'
cases = [
    's = "hello"; s[0:1] = "J"',
    's = "hello"; del s[0]',
    't = (1, 2); t[0] = 3',
    'b = b"hello"; b[0] = 74',
]
for code in cases:
    try:
        exec(code)
    except TypeError as e:
        print(f"{code:28} -> {e}")
EOF
python forms.py

Output

s = "hello"; s[0:1] = "J"    -> 'str' object does not support item assignment
s = "hello"; del s[0]        -> 'str' object doesn't support item deletion
t = (1, 2); t[0] = 3         -> 'tuple' object does not support item assignment
b = b"hello"; b[0] = 74      -> 'bytes' object does not support item assignment

The traceback points at the assignment line; the carets under s[0] mark the subscript Python tried to write.

How to recognise the cause

What you seeLikely cause
The variable was created as text, such as name = 'hello'You are editing a string in place; build a new one
The variable came from input(), a file, a CSV cell or a JSON fieldYou expected a list but received a str; check type(value)
The message names 'tuple' or 'bytes' instead of 'str'Same rule for other immutable types; use a list or a bytearray
The assignment is inside a loop over charactersCollect the new characters in a list and join them once

print(type(value), repr(value)) just before the failing line confirms what the variable really holds. A value that repr() prints inside quotes is a string even when it looks like a list, such as '[1, 2, 3]' read from a text file; parse it with json.loads() instead of indexing into it.

Choosing a fix

  • Change one position: slicing, s[:i] + new + s[i + 1:], is the shortest and keeps the rest of the string.
  • Change known text: s.replace(old, new) replaces every occurrence; s.replace(old, new, 1) replaces only the first.
  • Change many positions: convert with list(s), edit the list, then "".join(chars). This is the usual pattern for character-by-character algorithms.
  • Binary data: a bytearray is the mutable counterpart of bytes and accepts item assignment with integers from 0 to 255.

Always bind the result to a name (s = s.replace("h", "J")). Calling s.replace(...) without assigning the result is a silent bug: the string stays the same and no error is raised.

Prevention

Treat every string operation as returning a new value and assign it. Type hints (name: str) plus a type checker such as mypy flag item assignment to a str before the code runs. When a function must modify a sequence in place, have it accept and return a list.

FAQ

Why are Python strings immutable?

Immutability lets Python hash strings, so they can be dictionary keys and set members, and lets one string object be shared safely between variables. Every string method that seems to change text returns a new string instead.

Is building a new string slow?

One new string per change is fine in normal code. When you change many characters in a loop, collect the parts in a list and call join() once at the end instead of concatenating repeatedly.

Do tuples and bytes raise the same error?

Yes, with their own type name, for example 'tuple' object does not support item assignment. Use a list or a bytearray when the data must change in place.

Sources