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