How can I closely achieve ?: from C++/C# in Python?

前端 未结 9 1975
滥情空心
滥情空心 2021-02-20 11:02

In C# I could easily write the following:

string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;

Is there a qu

9条回答
  •  清酒与你
    2021-02-20 11:44

    There are a few duplicates of this question, e.g.

    • Does Python have a ternary conditional operator?
    • What's the best way to replace the ternary operator in Python?

    In essence, in a general setting pre-2.5 code should use this:

     (condExp and [thenExp] or [elseExp])[0]
    

    (given condExp, thenExp and elseExp are arbitrary expressions), as it avoids wrong results if thenExp evaluates to boolean False, while maintaining short-circuit evaluation.

提交回复
热议问题