Logical Operators on String in Python?


Python logical operator “and” and “or” can be applied on strings. An empty string returns a Boolean value of False. Let’s first understand the behaviour of these two logical operator “and” and “or”.

And operator

 Return the first falsey value if there are any, else return the last value in the expression or operator: Return the first truthly value if there are any, else return the last value in the expression.

Operation
Result
X and y
If x is false, then y else x
X and y
If x is false, then x, else y
Not x
If x is false, then true, else false

Below is is the program to demonstrate the use of logical operators on string in python −

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)

output

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

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements