This is for Python 2.6.
I could not figure out why a and b are identical:
>>> a = "some_string"
>>> b = "some_string"
>>> a is b
True
But if there is a space in the string, they are not:
>>> a = "some string"
>>> b = "some string"
>>> a is b
False
If this is normal behavior, could someone please explain what is going on.
Edit: Disclaimer ! This is not being used to check for equality. I actually wanted to explain to someone else that "is" is only to check identity, not equality. And from the documentation I had understood that references created in this way will be different, that a new string will be created each time. The very first example I gave threw me off when I couldn't prove my own point!
Edit: I understand that this is not a bug, and interning was a new concept for me. This seems to be a good explanation.
The is keyword is used to test if two variables refer to the same object. The test returns True if the two objects are the same object. The test returns False if they are not the same object, even if the two objects are 100% equal. Use the == operator to test if two variables are equal.
The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and !=
Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object.
The “is keyword” is used to test whether two variables belong to the same object. The test will return True if the two objects are the same else it will return False even if the two objects are 100% equal. Note: The == operator is used to test if two objects are the same.
Python may or may not automatically intern strings, which determines whether future instances of the string will share a reference.
If it decides to intern a string, then both will refer to the same string instance. If it doesn't, it'll create two separate strings that happen to have the same contents.
In general, you don't need to worry about whether this is happening or not; you usually want to check equality, a == b
, not whether they're the same object, a is b
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With