Yes, it was added in version 2.5. It's frowned upon by some pythonistas, so keep that in mind.
The syntax is:
a if test else b
First test is evaluated, then either a or b is returned based on the Boolean value of test;
if test evaluates to True a is returned, else b is returned.
For example:
>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
Official documentation:
本文介绍了Python中类似于C语言的三元运算符 ?: 的使用方法。这种语法是在Python 2.5版本中引入的,并提供了简洁的条件判断方式。例如,'true' if True else 'false' 返回 'true';反之返回 'false'。对于Python开发者来说,这是一种快速进行条件选择的有效手段。
454

被折叠的 条评论
为什么被折叠?



