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

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

    By the way, j0rd4n, you don't (please don't!) write code like this in C#. Apart from the fact that the IsDefaultOrNull is actually called IsNullOrEmpty, this is pure code bloat. C# offers the coalesce operator for situations like these:

    string stringValue = otherString ?? defaultString;
    

    It's true that this only works if otherString is null (rather than empty) but if this can be ensured beforehand (and often it can) it makes the code much more readable.

提交回复
热议问题