a = "Dog"
b = "eats"
c = "treats"
print a, b, c
# Dog eats treats
print a + " " + b + " " + c
# Dog eats treats
print a
# Dog
a = a + " " + b + " " + c
print a
# Dog eats treats
# !!!
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.
字符串对象本身是不可变的。
指向字符串的变量
a
是可变的。考虑:
第一个
a
指向字符串“Dog”。然后将变量a
改为指向新字符串“Dog eats treats”。你并没有真的把绳子“狗”变异。字符串是不可变的,变量可以指向它们想要的任何位置。变量a指向对象“Dog”。最好将Python中的变量看作一个标记。您可以将标记移动到不同的对象,这就是您将
a = "dog"
更改为a = "dog eats treats"
时所做的操作。然而,不变性指的是对象,而不是标记。
如果您试图
a[1] = 'z'
将"dog"
变成"dzg"
,您将得到错误:因为字符串不支持项赋值,所以它们是不可变的。
相关问题 更多 >
编程相关推荐