Python String Immutability and Reconstruction
Core idea
Strings are immutable: their stored sequence cannot be changed through an index. Concatenation with + combines two strings into a result. To edit text, construct a result and assign it to a name; this is rebinding rather than modification of the original object.
The first string remains unchanged. The slice retains the suffix and the plus operator adds a different prefix.
Rebind without editing the original
name = "red"saved = namename = name + "-blue"print(saved)print(name)Both names initially refer to the same value. Rebinding name does not alter what saved refers to.
Intentional error: assign to a character
An indexed assignment to a string raises TypeError. Use "b" + word[1:] to build the intended text instead.
Common mistake
An assignment such as word = "bat" is legal; it changes the binding, not the original sequence. Do not confuse this with word[0] = "b".
Practice
Change the first character of "lamp" to "c" using a slice and concatenation, keeping the original in a separate name.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
String immutability
Check your understanding of string immutability.
What is printed?
word = "cat"saved = wordword = "bat"print(saved)What happens?
word = "cat"word[0] = "b"Which expression constructs "bag" from word = "tag"?
What does immutability mean for strings?