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

2024-05-01 21:15:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我的理解是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不应该阻止赋值吗?我可能遗漏了什么。

知道吗?


Tags: 字符串代码printtreats赋值dog遗漏eats
3条回答

字符串对象本身是不可变的。

指向字符串的变量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.

第一个a指向字符串“Dog”。然后将变量a改为指向新字符串“Dog eats treats”。你并没有真的把绳子“狗”变异。字符串是不可变的,变量可以指向它们想要的任何位置。

变量a指向对象“Dog”。最好将Python中的变量看作一个标记。您可以将标记移动到不同的对象,这就是您将a = "dog"更改为a = "dog eats treats"时所做的操作。

然而,不变性指的是对象,而不是标记。


如果您试图a[1] = 'z'"dog"变成"dzg",您将得到错误:

TypeError: 'str' object does not support item assignment" 

因为字符串不支持项赋值,所以它们是不可变的。

相关问题 更多 >