Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

I've got a Python program where two variables are set to the value 'public'. In a conditional expression I have the comparison var1 is var2 which fails, but if I change it to var1 == var2 it returns True.

Now if I open my Python interpreter and do the same "is" comparison, it succeeds.

>>> s1 = 'public' >>> s2 = 'public' >>> s2 is s1 True 

What am I missing here?

like image 757
jottos Avatar asked Oct 01 '09 15:10

jottos


People also ask

What happens when you compare strings?

In String, the == operator is used to comparing the reference of the given strings, depending on if they are referring to the same objects. When you compare two strings using == operator, it will return true if the string variables are pointing toward the same java object. Otherwise, it will return false .

How do you compare two strings explain different ways to compare?

We can compare String in Java on the basis of content and reference. It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc. There are three ways to compare String in Java: By Using equals() Method.

What is the purpose of string compare string function?

compare() is a public member function of string class. It compares the value of the string object (or a substring) to the sequence of characters specified by its arguments. The compare() can process more than one argument for each string so that one can specify a substring by its index and by its length.

How do you compare two strings whether they are equal or not?

The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.


1 Answers

is is identity testing, == is equality testing. what happens in your code would be emulated in the interpreter like this:

>>> a = 'pub' >>> b = ''.join(['p', 'u', 'b']) >>> a == b True >>> a is b False 

so, no wonder they're not the same, right?

In other words: a is b is the equivalent of id(a) == id(b)

like image 178
SilentGhost Avatar answered Oct 13 '22 00:10

SilentGhost