问题
I'm using python 2.7.2 with built-in IDLE on windows 7 x64, and found a very strange thing:
>>> a = "aaa"
>>> b = "aaa"
>>> print a is b
True
>>> print a == b
True
>>> print "%s , %s" % (id(a), id(b))
43872224 , 43872224
>>>
This is normal, but, if the string contains a space:
>>> x = "x x"
>>> y = "x x"
>>> print x is y
False
>>> print x == y
True
>>> print "%s , %s" % (id(x), id(y))
43872008 , 43872128
>>>
Notice x is y
is False
! And they have different ids!
I tried these code in PyCharm, everything returns True
, so I think this is may be a bug of IDLE.
Isn't it? Or do I miss something?
回答1:
Python's is operator actually checks to see if the parameters it's passed are the same object, so in this case whilst they are the same value they're not the same object.
This has actually been discussed here before: with a lot more detail as well, worth checking out.
回答2:
All that this means is that IDLE implements different string interning policies than the interpreter's, or PyCharm's, defaults. If the strings are interned, then two equal strings will be the same string - ie, a == b
will imply a is b
. If they are not, then you can have the former without the latter, much like with other python objects:
>>> a = ['']
>>> b = ['']
>>> a is b
False
>>> a == b
True
EDIT: As far as I can tell by experimenting, the interactive interpreter does not interning these strings. However, running it as a .py script does intern them. This is most likely Python treating strings read from STDIN or a disk file differently to string literals in a source code file.
来源:https://stackoverflow.com/questions/9361341/compare-two-same-strings-but-get-different-results-in-idle