Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python의 문자열에 대한 논리 연산자?

<시간/>

Python 논리 연산자 "and" 및 "or"는 문자열에 적용할 수 있습니다. 빈 문자열은 False의 부울 값을 반환합니다. 먼저 이 두 논리 연산자 "and"와 "or"의 동작을 이해합시다.

연산자

있으면 첫 번째 false 값을 반환하고, 그렇지 않으면 표현식 또는 연산자의 마지막 값을 반환합니다. 있으면 첫 번째 true 값을 반환하고, 그렇지 않으면 표현식의 마지막 값을 반환합니다.

작업
결과
X 및 y
x가 거짓이면 y가 아니면 x
X와 Y
x가 거짓이면 x, 그렇지 않으면 y
x 아님
x가 거짓이면 참, 그렇지 않으면 거짓

아래는 파이썬에서 문자열에 대한 논리 연산자의 사용을 보여주는 프로그램입니다 -

str1 = ""
str2 = "python"
print(repr(str1 and str2))
print(repr(str2 and str1))
print(repr(str1 or str2))
print(repr(str2 or str1))
str1 = "Hello "
print(repr(str1 and str2))
print(repr(str2 and str1))
print(repr(str1 or str2))
print(repr(str2 or str1))
print(repr(not str1))
str2 = ""
print(repr(not str2))
str2 = "hello"
print("Hello == hello: ", str1 == str2)

출력

''
''
'python'
'python'
'python'
'Hello '
'Hello '
'python'
False
True
Hello == hello: False