Using is statement for strings

Question:

Can someone explain why I am getting following outputs? (I know this code has SyntaxWarning.)

>>> a = 'book'
>>> a is 'book'
True
>>> a = 'two book'
>>> a is 'two book'
False

I was expecting same result for both code snippet.

Asked By: m.r

||

Answers:

When comparing any 2 objects with "is" in python, you actually check the storage allocation of the 2 objects.

When creating a string, python tries to optimize the storage by using the same allocation for both. but this behavior isn’t always consistent, for it might be different for other strings.

I notices this behavior changes when using a space (" ") as a part of the string.

Anyways, you should compare objects with "==" and not "is". This way, the comparison will use the "eq" method from the class of the object, as it should.
Or you may implement this method by yourself if you’d like to (using inheritance and overriding)

Answered By: Matan Bendak
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.