猿问

Python字符串不是不可变的吗?那为什么+“”+ b有效呢?

我的理解是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不应该阻止这项任务吗?我可能错过了一些东西。


任何的想法?

Python字符串不是不可变的吗?那为什么+“”+ b有效呢?

梵蒂冈之花
浏览 1323回答 3
3回答

陪伴而非守候

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

白衣染霜花

首先a指向字符串“狗”。然后你改变了变量a以指向一个新的字符串“Dog eats treats”。你实际上并没有改变字符串“Dog”。字符串是不可变的,变量可以指向他们想要的任何东西。

杨魅力

字符串对象本身是不可变的。a指向字符串的变量是可变的。考虑:a = "Foo"# a now points to "Foo"b = a# b points to the same "Foo" that a points toa = a + a# a points to the new string "FooFoo", but b still points to the old "Foo"print aprint b# Outputs:# FooFoo# Foo# Observe that b hasn't changed, even though a has.
随时随地看视频慕课网APP

相关分类

Python
我要回答