0
s="wall"
d="WALL".lower()

s is d returns False. s and d are having the same string. But Why it returned False?

5 Answers5

2

== 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.

Eevee
  • 47,412
  • 11
  • 95
  • 127
2

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.

Sinkingpoint
  • 7,449
  • 2
  • 29
  • 45
1

"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.

Radosław Roszkowiak
  • 6,381
  • 3
  • 15
  • 27
  • 1
    Good answer, but it would be better to either omit the last part or explain it. The way it is might be confusing to beginners. – glglgl Aug 17 '14 at 07:18
0

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. ==

Community
  • 1
  • 1
nevets
  • 4,631
  • 24
  • 40
0

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.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578