반응형

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/

 

Logical Operators on String in Python - GeeksforGeeks

For strings in python, boolean operators (and , or, not) work. Let us consider the two strings namely str1 and str2 and try boolean operators… Read More »

www.geeksforgeeks.org

 

반응형