Python中有三元运算符吗?

by LauCyun Feb 11,2016 16:29:06 4,315 views

If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?

语法如下:

[on_true] if [expression] else [on_false]

根据expression的布尔值来判断返回的是on_true还是on_false;如果expression为真则返回on_true,反之则返回on_false

来个大栗子:

>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'

官方文档:

Tags