Sign in to follow this  
theOcelot

Python equality operators and strings

Recommended Posts

theOcelot    498
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
SiCrane    11839
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
mikeman    2942
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
pinacolada    834
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this