TryBugHunt

TypeError: 'str' object does not support item assignment

TypeError: 'str' object does not support item assignment in Python means you tried to change one character of a string in place. Python strings are immutable — you build a new string instead.

PythonPattern: Mutation and copying bugs

How do I fix TypeError: 'str' object does not support item assignment?

TypeError: 'str' object does not support item assignment means you tried to change one character with text[i] = "x". Python strings cannot be changed in place. Build a new string instead: word = "H" + word[1:], s = s.replace(" ", "_"), or convert with chars = list(s), edit the list, then s = "".join(chars).

  1. 1. Find the index assignmentLook for a line like s[i] = ... where s is a string. That is the line to rewrite.
  2. 2. Use replace for patternsIf you are swapping one character for another everywhere, s.replace(old, new) does it in one call.
  3. 3. Use a list for editsFor many scattered edits, convert with list(s), change items, then join back with "".join(chars).

What does TypeError: 'str' object does not support item assignment mean?

Reading text[0] is fine; writing text[0] = "H" is not. Strings, tuples and ints cannot be modified after creation, so every "change" is really creating a new value and rebinding the name to it. The same message for a tuple means the same thing.

Why does TypeError: 'str' object does not support item assignment happen?

1. Changing one character

Slicing builds the new string from the pieces around the change.

Breaks

word = "hello"
word[0] = "H"

Works

word = "H" + word[1:]
# or: word = word.capitalize()

2. Replacing characters in a loop

Index assignment does not work, but str.replace or a join over a generator does.

Breaks

for i in range(len(s)):
    if s[i] == " ":
        s[i] = "_"

Works

s = s.replace(" ", "_")

3. Many edits to the same string

Convert to a list once, edit freely, then join back.

Breaks

s[2] = "x"
s[5] = "y"

Works

chars = list(s)
chars[2] = "x"
chars[5] = "y"
s = "".join(chars)

How to find it in your own code

Any time you want to modify a string, write it as s = <new string built from s>. If the edits are scattered, list(s) → edit → "".join(...) is the standard pattern.

Try it: fix this bug

easy

capitalize_name("asha") crashes: TypeError: 'str' object does not support item assignment.

def capitalize_name(name):
    name[0] = name[0].upper()
    return name
Open with hintsRuns in your browser. No account needed.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.