Logical Operations on String in Python
Last Updated :
14 Mar, 2024
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'
print ( repr (str1 and str2))
print ( repr (str2 and str1))
print ( repr (str1 or str2))
print ( repr (str2 or str1))
str1 = 'for'
print ( repr (str1 and str2))
print ( repr (str2 and str1))
print ( repr (str1 or str2))
print ( repr (str2 or str1))
str1 = 'geeks'
print ( repr ( not str1))
str1 = ''
print ( repr ( not str1))
|
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:
- Python considers empty strings as having a boolean value of the ‘false’ and non-empty strings as having a boolean value of ‘true’.
- 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
- 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.
Please Login to comment...