为什么一行if语句没有给出例外结果

2024-04-27 03:45:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在我的程序中使用一行if条件,但它没有在else后面显示字符串,我认为这是因为语句为True,程序认为如果语句为false,则必须执行else后面的代码。你知道吗

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


Tags: 字符串in程序falsetrueaddedgetstring
1条回答
网友
1楼 · 发布于 2024-04-27 03:45:35

它与运算符优先级有关,整个+在第一个if-else之前求值。你知道吗

试试这个

string = "wow"
string = (string + "omg" if string == "wow" else "") + ("why this doesn't get added?" if 1 == 1 else "")

print(string)

输出:

wowomgwhy this doesn't get added?

您的原始代码相当于

string = (string + "omg" if string == "wow" else ("" + "why this doesn't get added?" if 1 == 1 else ""))

相关问题 更多 >