Jump to content
  • Advertisement
Sign in to follow this  
theOcelot

Python equality operators and strings

This topic is 3654 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
>>> 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
>>>

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
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!