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:
The 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.
- xyz
- Incorrect! Think about the values of s1 and s2 before line 3, then use those to determine the value of s1 in line 3. Try again.
- xyxyz
- Correct! The right side of the assignment statement is evaluated, then s1 is redefined to be equal to that, so s1 becomes xyxyz.
- xy xy z
- Incorrect! No spaces are added during concatenation. Try again.
- There is an error
- Incorrect! The right side of the assignment statement is evaluated, then s1 is redefined to be equal to that. Try again.
11-9-4: Given the following code segment, what is the value of the string s1 after the code is executed?
s1 = 'xy'
s2 = s1
s1 = s1 + s2 + 'z'
- Ball
- Incorrect! Assignment is not allowed with strings. Try again.
- Call
- Incorrect! Assignment is not allowed with strings. Try again.
- C
- Incorrect! Assignment is not allowed with strings. Try again.
- Nothing, there is an error
- Correct! Strings are immutable.
11-9-5: What is printed by the following statements:
s = "Ball"
s[0] = "C"
print(s)