pythonstringboolean-operations

Using "and" and "or" operator with Python strings


I don't understand the meaning of the Python code line:

parameter and (" " + parameter) or ""

which is using strings along with logical operators and and or. Also the type of the variable parameter is a string.

In this context, as I can't imagine a case where usage of boolean operators on strings would make sense, I want to ask the question:

Why would one want to use logical and and or operators with python strings in general and especially which sense does it make in the case of the above expression?

The answers on stackoverflow to the question How do "and" and "or" act with non-boolean values? and the up to now given answers explain what the above line of code does, but are still missing to address the question "Why would one want to use logical and and or operators with python strings in general and especially which sense does it make in the case of the above expression (compared to another possible options for writing code to achieve the same effect)?

The above question addresses the specific case of logical and and or operators applied to strings which wasn't addressed yet by another questions present on stackoverflow, so isn't a duplicate one.


Solution

  • 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:

    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:


    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.