Python equality operators and strings
Exactly what differences exist between the python == and is operators when used on strings? I just had an issue with comparing strings that was resolved when I switched from using is to ==. I'd like to avoid such annoyances in the future.
In Python the is operator is used to check if two objects are actually the same object. Sort of like comparing the address of objects in C++.
>>> x = 'this is a test'>>> y = x>>> x is yTrue>>> x == yTrue>>> y = 'this is a test'>>> x == yTrue>>> x is yFalse>>>
Quote:Original post by Oluseyi>>> x = 'this is a test'>>> y = x>>> x is yTrue>>> x == yTrue>>> y = 'this is a test'>>> x == yTrue>>> x is yFalse>>>
Actually, if you run this program properly and not in immediate-mode, you'll see that it prints 'True'
x='this is a test'y='this is a test'print x is y
Apparently that's because Python creates a single object for multiple literals that are the same. The immediate mode must screw something up, although I'm not sure what exactly.
Python is allowed to be clever and re-use the same object for equal string literals, but you definitely shouldn't depend on that. It's not a guarantee.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement