The two variables refer to a string with the same content. Use is to compare why it is False? when the result is True,.

In

python, using is to compare two strings, why does the following result appear:

In [1]: x = "ab"
        y = "ab"
        x is y
Out[1]: True

In [2]: x = "a123b"
        y = "a123b"
        x is y
Out[2]: True

In [3]: x = "a,b"
        y = "a,b"
        x is y
Out[3]: False

In [4]: x = "-sharp1"
        y = "-sharp1"
        x is y
Out[4]: False
Mar.02,2021

is compares whether the id of two objects is the same.
when the two are integers: if the value is between [- 5256], the two variables use objects in the same object pool, so the address is the same; if the value exceeds this range, a new piece of memory has to be opened up when the value is defined, and the address is different;
when the two are strings: if the value contains only numbers and letters, the two are the same.
when the two are dictionaries, tuples, and lists, the two are inconsistent.

Menu