Python 字符串不是不可变的吗?那么为什么一个 + ""+ 工作? [英] Aren't Python strings immutable? Then why does a + " " + b work?
本文介绍了Python 字符串不是不可变的吗?那么为什么一个 + ""+ 工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的理解是 Python 字符串是不可变的.
My understanding was that Python strings are immutable.
我尝试了以下代码:
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 不应该阻止赋值吗?我可能遗漏了一些东西.
Shouldn't Python have prevented the assignment? I am probably missing something.
有什么想法吗?
推荐答案
第一个 a
指向字符串Dog".然后将变量 a
更改为指向一个新字符串Dog Eats Treats".您实际上并没有改变字符串Dog".字符串是不可变的,变量可以指向任何他们想要的.
First a
pointed to the string "Dog". Then you changed the variable a
to point at a new string "Dog eats treats". You didn't actually mutate the string "Dog". Strings are immutable, variables can point at whatever they want.
这篇关于Python 字符串不是不可变的吗?那么为什么一个 + ""+ 工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文