×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Logical Operators on String in Python

By IncludeHelp Last updated : December 08, 2024

In Python, the following are the logical operators,

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

Python logical operators with strings

Below are the logical operators (operations) with the Python 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.

Python Logical Operators with Strings: Examples

Consider the below-given examples to understand the working of logical operators with Python strings:

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!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.