python에서 if(("hello" or "world") in "hello world") 라고 하면 무엇일까?
true라고 뜰까? false라고 뜰까?
정답은 얼핏 봐서는 hello world안에 hello 또는 world가 있기에 true이다.
하지만 연산자 순위 및 논리식에 의해 그렇지 않다.
"hello" or "world"를 하면 true or true이기에 첫번째 true만 보고 바로 hello를 뱉어낸다.
"hello" and "world"는 둘다 true이기에 마지막으로 본 "world"만 뱉어낸다.
아래에 좀 더 자세한 코드를 보고 이해해보자.
선뜻 아무거나 다 해줄 것 같은 python이 이런 부분에서는 우리가 생각하는 것과 다름을 이해하자.
str1 = ''
str2 = 'geeks'
print(repr(str1 and str2)) # Returns str1
print(repr(str2 and str1)) # Returns str1
print(repr(str1 or str2)) # Returns str2
print(repr(str2 or str1)) # Returns str2
str1 = 'for'
print(repr(str1 and str2)) # Returns str2
print(repr(str2 and str1)) # Returns str1
print(repr(str1 or str2)) # Returns str1
print(repr(str2 or str1)) # Returns str2
str1='geeks'
print(repr(not str1)) # Returns False
str1 = ''
print(repr(not str1)) # Returns True
Output |
'' '' 'geeks' 'geeks' 'geeks' 'for' 'for' 'geeks' False True |
The output of the boolean operations between the strings depends on following things:
1. Python considers empty strings as having boolean value of ‘false’ and
non-empty string as having boolean value of ‘true’.
2. For ‘and’ operator if left value is true, then right value is checked and returned.
If left value is false, then it is returned
3. For ‘or’ operator if left value is true, then it is returned,
otherwise if left value is false, then right value is returned.
https://www.geeksforgeeks.org/g-fact-43-logical-operators-on-string-in-python/
'Basic > Python' 카테고리의 다른 글
Python2에서 range와 xrange 차이 (0) | 2019.10.27 |
---|---|
파이썬 tkinter 예제 (0) | 2019.09.11 |
파이썬 1,2, 다차원 배열 입력 받기 (0) | 2019.03.03 |
파이썬 matplotlib를 이용하여 plot 실시간 그래프 그리기 (0) | 2018.10.31 |
유입, 내부, 외부 키워드 검색어 크롤링 (0) | 2018.09.19 |