【发布时间】:2022-06-10 12:43:17
【问题描述】:
Python 中的字符串是不可变的,这意味着值不能更改。我正在测试该场景,但看起来原始字符串已被修改。我只是想理解这个概念
>>> s = 'String'
>>> i = 5
>>> while i != 0:
... s += str(i)
... print(s + " stored at " + str(id(s)))
... i -= 1
...
String5 stored at 139841228476848
String54 stored at 139841228476848
String543 stored at 139841228476848
String5432 stored at 139841228476848
String54321 stored at 139841228476848
>>> a = "hello"
>>> id(a)
139841228475760
>>> a = "b" + a[1:]
>>> print(a)
bello
>>> id(a)
139841228475312
【问题讨论】:
-
@MohamadGhaithAlzin:docs,其中之一:“字符串是 Unicode 代码点的不可变序列。”
-
The standard wisdom is that Python strings are immutable. You can't change a string's value, only the reference to the string.continue reading here -
@chouyangv3:你错了。 CPython 将字符串的核心数据存储在结构末尾的灵活数组成员中(它也可以将数据的其他副本存储在单独的数组中,但规范表示始终是内联分配的,与结构本身);如果字符串实际上被复制到一个新对象,
id会发生变化。 CPython 中的优化有时可以避免通过reallocing 进行复制,如果不能以其他方式检测到突变。 -
@chouyangv3:你需要了解 C 才能知道 CPython 参考解释器在这里做什么,特别是 flexible array members(在 C99 中标准化,但你可以在任何版本的 C 中模拟它们将长度为 1 的数组放在结构的末尾,并选择分配的不仅仅是
sizeof(thestruct),或者只是分配额外的并将指向结构后字节的指针转换为正确的类型;旧的str是前者, newstr[with variable width characters] 后者)。 -
@user2357112 为什么说它破坏了不变性?我们所看到的是,之后的对象与之前的对象具有相同的地址。这并不意味着它们是同一个对象。
标签: python python-3.x string immutability string-concatenation