如果在 Python 中 None ,是否有返回默认值的简写? [英] Is there shorthand for returning a default value if None in Python?
本文介绍了如果在 Python 中 None ,是否有返回默认值的简写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 C# 中,我可以说 x ??""
,如果 x 不为空,它会给我 x,如果 x 为空,它会给我空字符串.我发现它对处理数据库很有用.
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.
如果 Python 在变量中发现 None ,有没有办法返回默认值?
Is there a way to return a default value if Python finds None in a variable?
推荐答案
您可以使用 or
运算符:
You could use the or
operator:
return x or "default"
请注意,如果 x
是任何虚假值,包括空列表、0、空字符串或什至 datetime.time,这也会返回
(午夜)."default"
(0)
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).
这篇关于如果在 Python 中 None ,是否有返回默认值的简写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文