Delving into the Discrepancy of String Comparison: '==' vs 'is'
The act of comparing strings using either '==' or 'is' can occasionally yield contrasting results. This raises the question of why this disparity exists.
Two string variables may have the same value, yet 's1 == s2' consistently returns True, whereas 's1 is s2' sometimes returns False.
When interpreted in Python, similar comparisons succeed:
>>> s1 = 'text' >>> s2 = 'text' >>> s1 is s2 True
To understand this phenomenon, it's crucial to distinguish between identity testing ('is') and equality testing ('==').
In the example provided, what occurs is replicated in the interpreter as follows:
>>> a = 'pub' >>> b = ''.join(['p', 'u', 'b']) >>> a == b True >>> a is b False
The disparity arises because 'is' compares the object's identities (i.e., memory addresses), while '==' compares their values. In the scenario above, 'a' and 'b' have the same value but exist separately in memory.
Therefore, it's logical that 'a is b' would evaluate to False since they are distinct objects, even though their contents align. In essence, 'a is b' is akin to 'id(a) == id(b)'.
The above is the detailed content of Python String Comparison: When Does `==` Differ From `is`?. For more information, please follow other related articles on the PHP Chinese website!