Compare Two Same Strings But Get Different Results In IDLE
Solution 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.
Solution 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.
Post a Comment for "Compare Two Same Strings But Get Different Results In IDLE"