Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this string comparison returning False? [duplicate]

Tags:

python

string

Possible Duplicate:
String comparison in Python: is vs. ==

algorithm = str(sys.argv[1])
print(algorithm)
print(algorithm is "first")

I'm running it from the command line with the argument first, so why does that code output:

first
False
like image 986
temporary_user_name Avatar asked Dec 08 '12 22:12

temporary_user_name


People also ask

Why does == evaluate to false in Java?

If your examples, both strings do not have the same object references, so they return false, == are not comparing the characters on both Strings.

Does === return false?

Note that === never causes type coercion, but checks for correct types first and yields false if they are not equal!

When comparing strings Why is == not a good idea?

Using the “==” operator for comparing text values is one of the most common mistakes Java beginners make. This is incorrect because “==” only checks the referential equality of two Strings, meaning if they reference the same object or not.

How do you compare strings with equal?

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.


2 Answers

From the Python documentation:

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object.

This means it doesn't check if the values are the same, but rather checks if they are in the same memory location. For example:

>>> s1 = 'hello everybody'
>>> s2 = 'hello everybody'
>>> s3 = s1

Note the different memory locations:

>>> id(s1)
174699248
>>> id(s2)
174699408

But since s3 is equal to s1, the memory locations are the same:

>>> id(s3)
174699248

When you use the is statement:

>>> s1 is s2
False
>>> s3 is s1
True
>>> s3 is s2
False

But if you use the equality operator:

>>> s1 == s2
True
>>> s2 == s3
True
>>> s3 == s1
True

Edit: just to be confusing, there is an optimisation (in CPython anyway, I'm not sure if it exists in other implementations) which allows short strings to be compared with is:

>>> s4 = 'hello'
>>> s5 = 'hello'
>>> id(s4)
173899104
>>> id(s5)
173899104
>>> s4 is s5
True

Obviously, this is not something you want to rely on. Use the appropriate statement for the job - is if you want to compare identities, and == if you want to compare values.

like image 197
Blair Avatar answered Oct 16 '22 23:10

Blair


You want:

algorithm = str(sys.argv[1])
print(algorithm)
print(algorithm == "first")

is checks for object identity (think memory address). But in your case the the objects have the same "value", but are not the same objects.

Note that == is weaker than is. This means that if is returns True, then == will also return True, but the reverse is not always true.

like image 35
Petar Ivanov Avatar answered Oct 17 '22 01:10

Petar Ivanov