7.5. Strings are immutable¶
It is tempting to use the operator on the left side of an assignment, with the intention of changing a character in a string. For example:
greeting string is an example of an object and the character
you tried to assign is an example of an item. For now, think of an object as a
special virtual construction. Objects have special properties. Strings, for example,
are objects that hold a sequence of characters. An item is one of the values in a sequence.
The reason for the error is that strings are immutable, which means that you can’t modify an existing string. The best you can do is create a new string that is a variation on the original:
This example concatenates a new first letter onto a slice of
greeting. It has no effect on the original string.
Or, you can reassign an existing variable to a completely new string:
This example assigns the
greeting variable to represent a new string object.
The old string object is deleted in the process.