Python:为什么("hello"是"hello")评估为True? [英] Python: Why does ("hello" is "hello") evaluate as True?

查看:131
本文介绍了Python:为什么("hello"是"hello")评估为True?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么"hello" is "hello"在Python中生成True?

Why does "hello" is "hello" produce True in Python?

我在此处阅读了以下内容:

如果两个字符串文字相等,则将它们放在相同的位置 内存位置.字符串是一个不变的实体.没有伤害可以 完成.

If two string literals are equal, they have been put to same memory location. A string is an immutable entity. No harm can be done.

那么每个Python字符串在内存中只有一个位置吗?听起来很奇怪.这是怎么回事?

So there is one and only one place in memory for every Python string? Sounds pretty strange. What's going on here?

推荐答案

Python(如Java,C,C ++ 、. NET)使用字符串池/内联.解释器意识到"hello"与"hello"相同,因此它优化并使用了内存中的相同位置.

Python (like Java, C, C++, .NET) uses string pooling / interning. The interpreter realises that "hello" is the same as "hello", so it optimizes and uses the same location in memory.

另一个礼物:"hell" + "o" is "hello" ==> True

Another goodie: "hell" + "o" is "hello" ==> True

这篇关于Python:为什么("hello"是"hello")评估为True?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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