TypeError
TypeError: 'str' object does not support item assignment
Traceback
Traceback (most recent call last):
File "main.py", line 2, in <module>
name[0] = "H"
TypeError: 'str' object does not support item assignmentWhat causes this error
An attempt was made to modify a character in a string using index assignment (e.g., s[0] = 'X'). Python strings are immutable and cannot be modified in place.
How to fix it
Create a new string with the desired changes. Use slicing: `s[:i] + new_char + s[i+1:]`. Use `.replace()` for simple substitutions. Convert to list, modify, and join back. Use bytearray for mutable byte sequences.
Code that causes this error
name = "hello" name[0] = "H"
Fixed code
name = "hello"
name = "H" + name[1:]
# or: name = name.replace("h", "H", 1)About TypeError
This TypeError is raised when you try to modify a character in a string using index assignment. Strings in Python are immutable — once created, their contents cannot be changed. This is a fundamental design decision in Python: strings, tuples, bytes, and frozensets are all immutable.
The immutability enables strings to be hashable (usable as dict keys and set members) and allows Python to optimize memory by reusing identical string objects. To modify a string, you must create a new string. Common approaches include using string slicing and concatenation, converting to a list of characters and back, using `.replace()` for simple substitutions, or using `bytearray` for mutable byte sequences.
For heavy string manipulation, the `io.StringIO` class provides efficient append operations.
Common scenarios
Performing operations between incompatible types like strings and integers
Calling methods that return None and chaining operations on the result
Passing the wrong number or type of arguments to a function
Using bracket notation on objects that do not support indexing