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
If your examples, both strings do not have the same object references, so they return false, == are not comparing the characters on both Strings.
Note that === never causes type coercion, but checks for correct types first and yields false if they are not equal!
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With