You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中字符串是否不可变?为何整体重新赋值无报错?

Why can I reassign a string variable but not modify individual characters?

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 variable a reference (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:

  1. A brand new string object ('David') is created in memory.
  2. The variable a is updated to reference this new object instead of the old one.
  3. 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 tag a on a sealed box labeled "Emiliano". You can't open the box to change what's inside (immutability).
  • a = 'David' peels the name tag a off 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:43:48