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

前端 未结 9 1974
滥情空心
滥情空心 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:30

    You can take advantage of the fact that logical expressions return their value, and not just true or false status. For example, you can always use:

    result = question and firstanswer or secondanswer
    

    With the caveat that it doesn't work like the ternary operator if firstanswer is false. This is because question is evaluated first, assuming it's true firstanswer is returned unless firstanswer is false, so this usage fails to act like the ternary operator. If you know the values, however, there is usually no problem. An example would be:

    result = choice == 7 and "Seven" or "Another Choice"
    

提交回复
热议问题