In C#, I can say x ?? "", which will give me x if x is not null, and the empty string if x is null. I’ve found it useful for working with databases.
Is there a way to return a default value if Python finds None in a variable?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You could use the or operator:
return x or "default"
Note that this also returns "default" if x is any falsy value, including an empty list, 0, empty string, or even datetime.time(0) (midnight).
Method 2
return "default" if x is None else x
try the above.
Method 3
You can use a conditional expression:
x if x is not None else some_value
Example:
In [22]: x = None In [23]: print x if x is not None else "foo" foo In [24]: x = "bar" In [25]: print x if x is not None else "foo" bar
Method 4
You’ve got the ternary syntax x if x else '' – is that what you’re after?
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0