开发者

Difference between `is` and `==`? [duplicate]

This question already has answers here: 开发者_运维知识库 Closed 12 years ago.

Possible Duplicate:

Python ‘==’ vs ‘is’ comparing strings, ‘is’ fails sometimes, why?

In Python, what is the difference between these two statements:

if x is "odp":

if x == "odp":


The == operator tests for equality

The is keyword tests for object identity; whether we are talking about the same object. Note that multiple variables may refer to the same object.


The is operator compares the identity while the == operator compares the value. Essentially x is y is the same as id(x) == id(y)


For implementation reasons, "odp" is a bad example, but you should not use is unless you want the possibility of two identical strings to evaluate to false:

>>> lorem1 = "lorem ipsum dolor sit amet"
>>> lorem2 = " ".join(["lorem", "ipsum", "dolor", "sit", "amet"])
>>> lorem1 == lorem2
True
>>> lorem1 is lorem2
False

As others have said, is tests identity, not equality. In this case, I have two separate strings with the same contents. However, you should not depend on this either:

>>> odp1 = "odp"
>>> odp2 = "".join(["o", "d", "p"])
>>> odp1 == odp2
True
>>> odp1 is odp2
True 

In other words, you should never use is to compare strings.

P.S. In Python 2.7.10 >>> odp1 is odp2 returns False.


See here

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜