Python
Error Handling
String Immutability
Programming
Debugging

'str' object does not support item assignment

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

The error 'str' object does not support item assignment appears when Python code tries to change one character inside an existing string. That operation feels natural if you are thinking of strings as mutable arrays, but Python strings are immutable.

Immutability means the contents of a str cannot be changed in place. You can create a new string based on the old one, but you cannot overwrite a single index the way you would with a list.

Why the Error Happens

This line raises the error immediately:

python
name = "mark"
name[0] = "M"

Python allows indexing for reading:

python
print(name[0])  # m

But it does not allow indexing for writing. The interpreter blocks the assignment because a str object is fixed after creation.

This behavior is different from a list:

python
letters = ["m", "a", "r", "k"]
letters[0] = "M"
print(letters)  # ['M', 'a', 'r', 'k']

Lists are mutable. Strings are not.

The Right Fix: Build a New String

When you need a changed version of a string, construct a new one. For a single-character replacement, slicing is often the clearest option:

python
1name = "mark"
2updated = "M" + name[1:]
3
4print(updated)  # Mark

The original string is unchanged, and updated points to a new string object.

If the position is dynamic, slicing still works:

python
1text = "hello"
2index = 1
3replacement = "a"
4
5updated = text[:index] + replacement + text[index + 1:]
6print(updated)  # hallo

That pattern is the closest equivalent to "assigning" into a string.

When Many Changes Are Needed

If you need to change many characters, converting to a list and joining back into a string is usually easier:

python
1text = "banana"
2chars = list(text)
3
4chars[0] = "B"
5chars[3] = "A"
6
7updated = "".join(chars)
8print(updated)  # BanAna

This works because the list holds mutable elements. After all edits are complete, "".join(...) creates the final string.

If the data is really binary or byte-oriented, use bytearray instead of fighting immutable text types:

python
data = bytearray(b"abc")
data[1] = ord(b"Z")
print(data)  # bytearray(b'aZc')

That is not a substitute for normal Unicode text processing, but it is the right tool when in-place byte mutation is genuinely required.

For repeated substitutions based on content rather than position, use string methods instead:

python
1text = "error: file missing"
2updated = text.replace("error", "warning")
3
4print(updated)  # warning: file missing

Methods such as .replace(), .strip(), and .upper() return new strings rather than editing the original.

Understanding Immutability in Practice

Python makes strings immutable for good reasons:

  • strings can be shared safely between different parts of a program
  • many optimizations become simpler
  • hashable string objects can be used as dictionary keys

This design does mean you need a different mindset. Instead of "change the string," think "derive the string I want from the current one."

Example in a Real Function

Here is a small helper that capitalizes a character at a given position:

python
1def capitalize_at(text, index):
2    if index < 0 or index >= len(text):
3        raise IndexError("index out of range")
4    return text[:index] + text[index].upper() + text[index + 1:]
5
6
7print(capitalize_at("python", 3))  # pytHon

The function never mutates text. It creates and returns a new string with the requested change.

Common Pitfalls

The most common pitfall is assuming that strings behave like lists because both are indexable. Indexing for reading does not imply assignment is allowed.

Another issue is forgetting that string methods return new values. Code such as text.replace("a", "b") does nothing useful unless you assign the result back to a variable.

Developers also sometimes convert to a list for a one-character change when a slice expression would be simpler and clearer. Lists are useful for many edits, but they are unnecessary for every case.

Finally, be careful when working with bytes. bytes objects are also immutable, while bytearray is mutable. The same general rule applies: choose the data type that matches whether mutation is needed.

Summary

  • The error happens because Python strings are immutable.
  • You can read text[index], but you cannot assign to it.
  • Use slicing, .replace(), or list conversion plus "".join(...) to produce a new string.
  • String methods return new values and do not modify the original object.
  • Think in terms of creating updated strings rather than mutating existing ones.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.