Home >Backend Development >Python Tutorial >Python String Comparison: When Does `==` Differ From `is`?

Python String Comparison: When Does `==` Differ From `is`?

Barbara Streisand
Barbara StreisandOriginal
2024-12-26 16:39:14617browse

Python String Comparison: When Does `==` Differ From `is`?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn