• Advertisement
Sign in to follow this  

Python equality operators and strings

This topic is 3475 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
Advertisement
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++.

Share this post


Link to post
Share on other sites
Quote:
Original post by Oluseyi
>>> x = 'this is a test'
>>> y = x
>>> x is y
True
>>> x == y
True
>>> y = 'this is a test'
>>> x == y
True
>>> x is y
False
>>>


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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement