Search code examples
pythonpython-3.xternary-operatorstring-concatenation

Why ternary condition not working perfectly for string concatenation


I saw a peculiar behavior in python when using ternary operator in string concatenation -

>>> foo = "foo"
>>> foo.upper()
'FOO'
>>> bar = 2
>>> "" if bar is 0 else str(bar)
'2'
>>> foo.upper() + "_" + "" if bar is 0 else str(bar)
'2'

With the above code I was expecting it should output as FOO_2 but only showing 2. Though I can achieve the output with the below code. Can anyone explain why it is not working with + ?

>>> "{}_{}".format(foo.upper(), "" if bar is 0 else str(bar))
'FOO_2'

Solution

  • The operator precedence plays a crucial role here. The expression is evaluated as:

    (foo.upper() + "_" + "") if bar is 0 else str(bar)
    

    This is because conditional expressions precede addition and subtraction.

    Use parenthesis to enforce your desired evaluation order:

    foo.upper() + "_" + ("" if bar is 0 else str(bar))
    

    Or, what is probably even better is to decrease complexity by extracting a variable to avoid any possible confusion:

    postfix = "" if bar is 0 else str(bar)
    print(foo.upper() + "_" + postfix)