Python 字符串不是不可变的吗? [英] Python strings are not immutable?

查看:53
本文介绍了Python 字符串不是不可变的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到现在我相信 Python 字符串是不可变的,但是当我尝试这个时我感到困惑

<预><代码>>>>一种'你好,世界 !'>>>身份证(一)140521043795728>>>a+="d">>>身份证(一)140521043795728>>>a+="d">>>身份证(一)140521043795728>>>一种'你好世界!dd'

如果我使用 += 运算符,它不会更改对象 ID,尽管字符串已更改.在这种情况下发生了什么?

现在有点不同?https://ideone.com/eg1SIN

有人能解释一下这里发生了什么吗?

解决方案

id 返回一个整数值,该值对于您传递的对象是唯一的.如果 a 是对字符串 'hello world !' 的唯一引用,那么执行 a += "b" 可能会结束该字符串的生命周期字符串 'hello world !' 在创建字符串 'hello world !b' 之前,所以旧字符串的 ID 被重用(这是完全有效的行为).

添加对字符串 'hello world !' 的另一个引用(例如,通过在修改 a 之前执行 b = a)应该导致要发散的 ID.

till now I belived that Python strings are immutable but when I tried this I got confused

>>> a
'hello world !'
>>> id(a)
140521043795728
>>> a+="d"
>>> id(a)
140521043795728
>>> a+="d"
>>> id(a)
140521043795728
>>> a
'hello world !dd'

if I use += operator, it doesn't change the object id although string has changed. what is happening in this case?

now this is bit different? https://ideone.com/eg1SIN

can somebody explain what is happening here?

解决方案

id returns an integer value that is unique to the object you pass it. If a is the only reference to the string 'hello world !', then doing a += "b" may end the lifetime of the string 'hello world !' before the string 'hello world !b' is created, so the ID of the old string is reused (which is perfectly valid behavior).

Adding another reference to the string 'hello world !' (for example, by doing b = a before modifying a) should cause the IDs to diverge.

这篇关于Python 字符串不是不可变的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆