Python 字符串不变性


在 python 中,字符串数据类型是不可变的。这意味着无法更新字符串值。我们可以通过尝试更新字符串的一部分来验证这一点,这将导致我们出错。

# Can not reassign 
t= "Newbiego"
print type(t)
t[0] = "M"

当我们运行上面的程序时,我们得到如下输出:


t[0] = "M"
TypeError: 'str' object does not support item assignment

我们可以通过检查字符串中字母位置的内存位置地址来进一步验证这一点。

.
x = 'banana'

for idx in range (0,5):
    print x[idx], "=", id(x[idx])

当我们运行上面的程序时,我们得到以下输出。正如你在上面看到的 a 和 a 指向同一位置。 N 和 N 也指向同一个位置。

b = 91909376
a = 91836864
n = 91259888
a = 91836864
n = 91259888