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

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

    It's never a bad thing to write readable, expressive code.

    if otherString:
       stringValue = otherString
    else:
       stringValue = defaultString
    

    This type of code is longer and more expressive, but also more readable and less likely to get tripped over or mis-edited down the road. Don't be afraid to write expressively - readable code should be a goal, not a byproduct.

    0 讨论(0)
  • 2021-02-20 11:27

    If you used ruby, you could write

    stringValue = otherString.blank? ? defaultString : otherString;
    

    the built in blank? method means null or empty.
    Come over to the dark side...

    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2021-02-20 11:32

    I also discovered that just using the "or" operator does pretty well. For instance:

    finalString = get_override() or defaultString
    

    If get_override() returns "" or None, it will always use defaultString.

    0 讨论(0)
  • 2021-02-20 11:39

    Chapter 4 of diveintopython.net has the answer. It's called the and-or trick in Python.

    0 讨论(0)
  • 2021-02-20 11:40

    In Python 2.5, there is

    A if C else B
    

    which behaves a lot like ?: in C. However, it's frowned upon for two reasons: readability, and the fact that there's usually a simpler way to approach the problem. For instance, in your case:

    stringValue = otherString or defaultString
    
    0 讨论(0)
提交回复
热议问题