我的理解是Python字符串是不可变的。我尝试了以下代码:a = "Dog"b = "eats"c = "treats"print a, b, c# Dog eats treatsprint a + " " + b + " " + c# Dog eats treatsprint a# Doga = a + " " + b + " " + cprint a# Dog eats treats# !!!Python不应该阻止这项任务吗?我可能错过了一些东西。任何的想法?Python字符串不是不可变的吗?那为什么+“”+ b有效呢?
3 回答

陪伴而非守候
TA贡献1757条经验 获得超8个赞
变量a指向对象“Dog”。最好将Python中的变量视为标记。您可以将标记移动到不同的对象,这是您在更改时所a = "dog"
执行的操作a = "dog eats treats"
。
但是,不变性是指对象,而不是标签。
如果你试图a[1] = 'z'
做"dog"
成"dzg"
,你会得到错误:
TypeError: 'str' object does not support item assignment"
因为字符串不支持项目赋值,因此它们是不可变的。

白衣染霜花
TA贡献1796条经验 获得超10个赞
首先a
指向字符串“狗”。然后你改变了变量a
以指向一个新的字符串“Dog eats treats”。你实际上并没有改变字符串“Dog”。字符串是不可变的,变量可以指向他们想要的任何东西。

杨魅力
TA贡献1811条经验 获得超6个赞
字符串对象本身是不可变的。
a指向字符串的变量是可变的。
考虑:
a = "Foo"
# a now points to "Foo"
b = a
# b points to the same "Foo" that a points to
a = a + a
# a points to the new string "FooFoo", but b still points to the old "Foo"
print a
print b
# Outputs:
# FooFoo
# Foo
# Observe that b hasn't changed, even though a has.
添加回答
举报
0/150
提交
取消