我的理解是Python字符串是不可变的。
我尝试了以下代码:
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
# !!!
Python不应该阻止赋值吗?我可能漏掉了什么。
有什么想法吗?
发布于 2012-02-01 23:00:03
第一个a
指向字符串“狗”。然后,您更改了变量a
以指向新字符串"Dog eats treats“。你实际上并没有改变“狗”这个字符串。字符串是不可变的,变量可以指向任何它们想要的东西。
发布于 2012-02-01 22:59:15
字符串对象本身是不可变的。
指向字符串的变量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.
发布于 2012-02-01 22:59:17
变量只是一个指向对象的标签。该对象是不可变的,但如果愿意,您可以使标签指向完全不同的对象。
https://stackoverflow.com/questions/9097994
复制相似问题