Logical Operators on String in Python

Python | Logical operators on String: Here, we are going to learn how logical operators (and, or, not) work with Strings in Python?
Submitted by IncludeHelp, on May 30, 2020

In Python, the following are the logical operators,

  • Logical AND (and)
  • Logical OR (or)
  • Logical NOT (not)

With strings,

  • An empty string means False as a Boolean value, while a non-empty string means True as a Boolean value.
  • For "and" operator: If the first operand is True, it checks the second operand and returns the second operand.
  • For "or" operator: If the first operand is False, it checks the second operand and returns the second operand.
  • For "and" operator: If the operand is an empty string, it returns True; False, otherwise.

Example 1:

# Logical Operators on String in Python

string1 = "Hello"
string2 = "World"

# and operator on string
print("string1 and string2: ", string1 and string2)
print("string2 and string1: ", string2 and string1)
print()

# or operator on string
print("string1 or string2: ", string1 or string2)
print("string2 or string1: ", string2 or string1)
print()

# not operator on string
print("not string1: ", not string1)
print("not string2: ", not string2)
print()

Output:

string1 and string2:  World
string2 and string1:  Hello

string1 or string2:  Hello
string2 or string1:  World

not string1:  False
not string2:  False

Example 2:

# Logical Operators on String in Python

string1 = "" # empty string
string2 = "World" # non-empty string

# Note: 'repr()' function prints the string with
# single quotes
# and operator on string
print("string1 and string2: ", repr(string1 and string2))
print("string2 and string1: ", repr(string2 and string1))
print()

# or operator on string
print("string1 or string2: ", repr(string1 or string2))
print("string2 or string1: ", repr(string2 or string1))
print()

# not operator on string
print("not string1: ", not string1)
print("not string2: ", not string2)
print()

Output:

string1 and string2:  ''
string2 and string1:  ''

string1 or string2:  'World'
string2 or string1:  'World'

not string1:  True
not string2:  False






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.