스트링 비교할 때 "=="랑 "is"가 다른 결과가 나오는 경우
조회수 2635회
var1, var2 두 변수가 같은 스트링 "public"을 저장하고 있을 때
var1 is var2
에서는 False
,
var1 == var2
에서는 True
를 return하는 프로그램을 봤는데요.
제가 실험해보니까 지금은 둘 다 True
를 return합니다.
왜 그런건가요?
소스코드
s1 = "public!"
s2 = "public"
print s1==s2
print s1 is s2
1 답변
-
is
와==
는 같지 않습니다.==
는 equality를,is
는 identity를 검사하지요.identity
는 현재 주소 값이라고 생각하시면 됩니다.따라서 둘 중 어느 방법이 더 좋냐는 질문은 경우에 따라 다르다 입니다.
밑에
is
와==
가 다른 결과를 내는 예제를 적어 두었으니 참고하세요.예제를 통해서 보면
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)
결과 :
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
댓글 입력