为什么三元条件不能完美地用于字符串连接

Why ternary condition not working perfectly for string concatenation

在字符串连接中使用三元运算符时,我在 python 中看到了一个奇怪的行为 -

>>> 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'

使用上面的代码,我期望它应该输出为 FOO_2,但只显示 2。虽然我可以用下面的代码实现输出。谁能解释为什么它不能与 + 一起使用?

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

operator precedence在这里起着至关重要的作用。表达式计算为:

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

这是因为条件表达式先于加法和减法。

使用括号强制执行您想要的评估顺序:

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

或者,可能更好的方法是将复杂性降低 extracting a variable 以避免任何可能的混淆:

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