Python 中的字符串是不可变的,这意味着不能更改值。但是,当在下面的示例中添加字符串时,原始字符串内存似乎被修改了,因为 id 保持不变:
>>> s = 'String'
>>> for i in range(5, 0, -1):
... s += str(i)
... print(f"{s:<11} stored at {id(s)}")
...
String5 stored at 139841228476848
String54 stored at 139841228476848
String543 stored at 139841228476848
String5432 stored at 139841228476848
String54321 stored at 139841228476848
相反,在下面的示例中,id 会发生变化:
>>> a = "hello"
>>> id(a)
139841228475760
>>> a = "b" + a[1:]
>>> print(a)
bello
>>> id(a)
139841228475312