我正在尝试在程序中使用if条件,但是在其他条件下它不会显示字符串,我认为这是因为语句为True,并且程序认为如果在其他条件下必须执行其他代码该陈述是错误的。
In [506]: string = "wow"
In [507]: string = string + "omg" if string == "wow" else "" + "why this doesn't get added?" if 1 == 1 else ""
In [508]: string
Out[508]: 'wowomg'
我希望string
是'wowomgwhy this doesn't get added?'
答案 0 :(得分:2)
这与运算符优先级有关,整个+
在第一个if-else
之前进行求值。
尝试
string = "wow"
string = (string + "omg" if string == "wow" else "") + ("why this doesn't get added?" if 1 == 1 else "")
print(string)
输出:
哇,为什么不添加?
您的原始代码等同于
string = (string + "omg" if string == "wow" else ("" + "why this doesn't get added?" if 1 == 1 else ""))