Boolean operators on a string in Python

str1 = ` `

str2 = `geeks`

 
# repr is used to print a string with quotes

 

 

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

 

 
# Nickhil Kumar Singh`s code (nickzuck_007)

Exit:

 `` `` `geeks`` geeks` `geeks` for`` for` `geeks` False True 
The output of logical operations between lines depends on the following:

  1. Python treats empty lines as boolean false and nonblank lines as boolean true.
  2. For the and operator, if the left value is true, the right value is checked and returned. If the left value is false, it is returned
  3. For the operator & # 39; or & # 39;, if the left value is true, it is returned, otherwise, if the left value is false, the right value is returned.

Note that bitwise operators (|, & amp;) do not work for lines.

This article courtesy of Nikhil Kumar Singh .

If you like Python.Engineering and would like to contribute, you can also write an article and mail it to [email protected] See your article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you`d like to share more information on the topic under discussion