Today we’ll be talking about string immutability.
Here you can watch the video version of this article:
Strings are immutable. Once defined, they can’t be changed.
We can’t change any of the characters. For example we can’t change Jake to Jane by changing ‘k’ to ‘n’. If we try, we’ll get a self-explanatory type error:
>>> name = "Jake"
>>> name[2] = "n"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
We can assign a new object to a variable, but this is not changing the string. This way we are just defining a new string and assigning it to the same variable:
>>> text = "I like soccer." # the string is assigned to text
>>> text = "I like tennis." # a new string is assigned to text
>>> text
'I like tennis.'
String immutability also means that you can’t delete a single character either. If we try to do that, using the del statement, we’ll get an error:
>>> name = "Steve"
>>> del name[2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object doesn't support item deletion
We can delete the whole string:
>>> del name
>>> name
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'name' is not defined