Python字符串不是一成不变的吗?那么为什么要加上+"" + b工作? [英] Aren't Python strings immutable? Then why does a + " " + b work?
本文介绍了Python字符串不是一成不变的吗?那么为什么要加上+"" + b工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的理解是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对待".您实际上并未更改字符串"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字符串不是一成不变的吗?那么为什么要加上+"" + b工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文