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

问题描述 投票:1回答:1

在字符串连接中使用三元运算符时,我在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'
python python-3.x ternary-operator string-concatenation
1个回答
4
投票

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)
© www.soinside.com 2019 - 2024. All rights reserved.