Krimson Krimson - 24 days ago 10
Python Question

Unusual behavior when using ternary operator to append to string

In python, when I append an empty string to a non empty string, the results are as expected

>>> "1234" + ""
>>> "1234"


But when I use a ternary operator like so, this is the output

>>> "1234" + "abcd" if True else ""
>>> "1234abcd"

>>> "1234" + "abcd" if False else ""
>>> ""


Why do I get an empty string in the second case instead of
"1234"
?

Answer

Just want to expand @BrenBarn's answer (which is correct): if You want to get desired behavior, You should do it like this:

"1234" + ("abcd" if False else "")

or,

"1234" + "abcd" if False else "1234" + ""
Comments