Python:为什么运算符“是"?和“=="有时可以互换字符串吗? [英] Python: Why operator "is" and "==" are sometimes interchangeable for strings?

查看:61
本文介绍了Python:为什么运算符“是"?和“=="有时可以互换字符串吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

可能的重复:
Python 中的字符串比较:is vs ==
Python 字符串实习
为什么在 Python 中使用=="或is"比较字符串有时会产生不同的结果?

我不小心将 is== 用于字符串,但我发现它们并不总是相同的.

<预><代码>>>>文件夹=语言环境/">>>Folder2 =语言环境/">>>文件夹是 Folder2错误的>>>文件夹 == 文件夹 2真的>>>文件 = "文件">>>文件 2 = "文件">>>文件是 File2真的>>>文件 == 文件 2真的>>>

为什么在一种情况下运算符可以互换而在另一种情况下不能?

解决方案

为了提高效率,短字符串被留存,因此将引用同一个对象,因此 is 为真.

这是CPython中的一个实现细节,绝对不能依赖.

Possible Duplicate:
String comparison in Python: is vs. ==
Python string interning
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?

I used accidentally is and == for strings interchangeably, but I discovered is not always the same.

>>> Folder = "locales/"
>>> Folder2 = "locales/"
>>> Folder is Folder2
False
>>> Folder == Folder2
True
>>> File = "file"
>>> File2 = "file"
>>> File is File2
True
>>> File == File2
True
>>> 

Why in one case operators are interchangeable and in the other not ?

解决方案

Short strings are interned for efficiency, so will refer to the same object therefore is will be true.

This is an implementation detail in CPython, and is absolutely not to be relied on.

这篇关于Python:为什么运算符“是"?和“=="有时可以互换字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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