Python中字符串是否不可变?为何整体重新赋值无报错?
Awesome question—this is a super common point of confusion when learning about Python's immutable types, so let's unpack it step by step.
First, let's clarify the key difference between variables and the objects they point to:
- When you run
a = 'Emiliano', you're doing two things: creating an immutable string object ('Emiliano') in memory, and making the variableareference (point to) that object. - The "immutable" rule applies to the string object itself, not the variable that points to it.
Why a[0] = 'r' throws an error
When you try a[0] = 'r', you're attempting to modify the existing string object that a points to. Since strings are immutable, Python doesn't allow you to change any part of that object after it's created—this is why you get the TypeError: 'str' object does not support item assignment.
Why a = 'David' works perfectly
When you run a = 'David', you're not modifying the original 'Emiliano' object at all. Instead:
- A brand new string object (
'David') is created in memory. - The variable
ais updated to reference this new object instead of the old one. - The original
'Emiliano'object is now orphaned (no variables point to it), so Python's garbage collector will eventually clean it up.
You can even verify this with the id() function, which shows the memory address of an object:
a = 'Emiliano' print(id(a)) # Outputs a unique memory address (e.g., 140697843245808) a = 'David' print(id(a)) # Outputs a completely different address—proof it's a new object
Quick analogy to make it stick
Think of variables like name tags, and string objects like sealed boxes.
a = 'Emiliano'sticks the name tagaon a sealed box labeled "Emiliano". You can't open the box to change what's inside (immutability).a = 'David'peels the name tagaoff the old box and sticks it on a new sealed box labeled "David". You're not altering either box—just moving the tag.
内容的提问来源于stack exchange,提问作者emiliano gramajo

