Open In App
Related Articles

Logical Operators on String in Python

Improve Article
Improve
Save Article
Save
Like Article
Like

For strings in python, boolean operators (and, or, not) work. Let us consider the two strings namely str1 and str2 and try boolean operators on them: 

Python3




str1 = ''
str2 = 'geeks'
  
# repr is used to print the string along with the quotes
  
# Returns str1
print(repr(str1 and str2))  
  
# Returns str1   
print(repr(str2 and str1)) 
  
# Returns str2     
print(repr(str1 or str2))   
  
# Returns str2   
print(repr(str2 or str1))       
  
str1 = 'for'
  
# Returns str2 
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))       
  
str1='geeks'
  
# Returns False
print(repr(not str1))          
  
str1 = '' 
  
# Returns True 
print(repr(not str1))          
  
  
# Coded by Nikhil Kumar Singh(nickzuck_007)


Output: 

''
''
'geeks'
'geeks'
'geeks'
'for'
'for'
'geeks'
False
True

Time Complexity: O(1) 
Auxiliary Space: O(1)

The output of the boolean operations between the strings depends on the following things: 

  1. Python considers empty strings as having a boolean value of the ‘false’ and non-empty strings as having a boolean value of ‘true’.
  2. For the ‘and’ operator if the left value is true, then the right value is checked and returned. If the left value is false, then it is returned
  3. For the ‘or’ operator if the left value is true, then it is returned, otherwise, if the left value is false, then the right value is returned.

Note that the bitwise operators (|, &) don’t work for strings. 

If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
 


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 11 Sep, 2023
Like Article
Save Article
Similar Reads
Related Tutorials