Skip to content

Computer Science · Ch 8 — Strings

String is Immutable

8.2.2

String is Immutable

Strings in Python are an immutable data type. Immutable means "unchangeable": once a string has been created, its contents can never be altered. You may read any character of it (as Section 8.2.1 showed), but you cannot overwrite, insert or delete characters inside the existing string object.

Any attempt to change a character in place is met with an error. Since indexing with [ ] can read a position, it is tempting to try assigning to that position — but Python refuses:

>>> s = "Hello World!"
>>> s[1] = 'a'          # trying to turn 'Hello' into 'Hallo'
TypeError: 'str' object does not support item assignment

The TypeError message says it precisely: a str object does not support item assignment — you cannot assign a new value to an individual item (character) of a string.

What immutability does and does not forbid

  • Forbidden: modifying the existing string object — e.g. s[1] = 'a'. …