Using "and" and "or" operator with Python strings [duplicate]

I don't understand the meaning of the line:

parameter and (" " + parameter) or ""

where parameter is string

Why would one want to use and and or operator, in general, with python strings?


Solution 1:

Suppose you are using the value of parameter, but if the value is say None, then you would rather like to have an empty string "" instead of None. What would you do in general?

if parameter:
    # use parameter (well your expression using `" " + parameter` in this case
else:
    # use ""

This is what that expression is doing. First you should understand what and and or operator does:

  • a and b returns b if a is True, else returns a.
  • a or b returns a if a is True, else returns b.

So, your expression:

parameter and (" " + parameter) or ""

which is effectively equivalent to:

(parameter and (" " + parameter)) or  ""
#    A1               A2               B
#           A                     or   B

How the expression is evaluated if:

  • parameter - A1 is evaluated to True:

    result = (True and " " + parameter) or ""
    
    result = (" " + parameter) or ""
    
    result = " " + parameter
    
  • parameter - A1 is None:

    result = (None and " " + parameter) or ""
    
    result = None or ""
    
    result = ""
    

As a general suggestion, it's better and more readable to use A if C else B form expression for conditional expression. So, you should better use:

" " + parameter if parameter else ""

instead of the given expression. See PEP 308 - Conditional Expression for motivation behind the if-else expression.

Solution 2:

Python considers empty strings as having boolean value of "false" and non-empty strings as having boolean value of "true".

So there're only two possible outcomes of the expression, i.e. for empty string and for non-empty string.

Second thing to notice is that which value of "or" and "and" operator are returned. Python does not return just true or false value, for strings and or/and operator it returns one of the strings (considering they have value of true or false). Python uses lazy approach:

For "and" operator if left value is true, then right value is checked and returned. if left value is false, then it is returned

For "or" operator if first value is true, then it is returned. otherwise if second value is false, then second value is returned

parameter = 'test'
print( parameter and (" " + parameter) or "" )

ouput: test

parameter = ''
print( parameter and (" " + parameter) or "" )

output:(empty string)