s="wall"
d="WALL".lower()
s is d
returns False
.
s and d are having the same string. But Why it returned False?
s="wall"
d="WALL".lower()
s is d
returns False
.
s and d are having the same string. But Why it returned False?
==
tests for equality. a == b
tests whether a
and b
have the same value.
is
tests for identity — that is, a is b
tests whether a
and b
are in fact the same object. Just don't use it except to test for is None
.
You seem to be misunderstanding the is
operator. This operator returns true if the two variables in question are located at the same memory location. In this instance, although you have two variables both storing the value "wall", they are still both distinct in that each has its own copy of the word.
In order to properly check String equality, you should use the ==
operator, which is value equality checking.
"is" keyword compares the objects IDs, not just whether the value is equal. It's not the same as '===' operator in many other languages. 'is' is equivalent to:
id(s) == id(d)
There are some even more interesting cases. For example (in CPython):`
a = 5
b = 5
a is b # equals to True
but:
c = 1200
d = 1200
c is d # equals to False
The conclusion is: don't use 'is' to compare values as it can lead to confusion.
By using is
your are comparing their identities, if you try print s == d
, which compares their values, you will get true.
Check this post for more details: String comparison in Python: is vs. ==
Use ==
to compare objects for equality. Use is
to check if two variables reference the exact same objects. Here s
and d
refer to two distinct string objects with identical contents, so ==
is the correct operator to use.