Sign in to follow this  
theOcelot

Python equality operators and strings

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
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

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