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

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

3
  • How is the 'is' keyword implemented in Python? Commented Aug 17, 2014 at 6:11
  • 4
    where did you learn about is? you should very, very rarely be using it. Commented Aug 17, 2014 at 6:12
  • @Eevee I came across is when I searched for string operations. Commented Aug 17, 2014 at 6:23

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

1 Comment

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.