If "==" and "is" are different results when comparing strings

Asked 2 years ago, Updated 2 years ago, 123 views

Var1 and var2 are storing the same string "public"

var1 is var2 for false, In var1 == var2 , True

I watched a program that returns. I experimented and now both return True. Why is that?

s1 = "public!"
s2 = "public"

print s1==s2
print s1 is s2

string python compare

2022-09-21 21:22

1 Answers

is and == are not the same.

== checks for quality and is checks for identity. identity is the current address value.

So the question of which way is better is different depending on the case.

Please refer to the examples below in which is and == produce different results.

If you look at the example,

str1 = "cat"
str2 = "".join("cat")
str3 = "".join(['c','a','t'])

print "str1 == str2:", str1==str2
print "str1 is str2:", str1 is str2

print "\nstr3 == str1:", str3==str1
print "str3 is str2", str3 is str2

print "\nid of str1:", id(str1)
print "id of str2:", id(str2)
print "id of str3:", id(str3)

Result:

str1 == str2: True
str1 is str2: False

str3 == str1: True
str3 is str2 False

id of str1: 4463102912
id of str2: 4463847504
id of str3: 4463847664


2022-09-21 21:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.