如果在 Python 中 None ,是否有返回默认值的简写?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13710631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there shorthand for returning a default value if None in Python?
提问by nfw
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.
在 C# 中,我可以说x ?? "",如果 x 不为空,它将给我 x,如果 x 为空,它将给我空字符串。我发现它对处理数据库很有用。
Is there a way to return a default value if Python finds None in a variable?
如果 Python 在变量中发现 None ,有没有办法返回默认值?
采纳答案by starhusker
You could use the oroperator:
您可以使用or运算符:
return x or "default"
Note that this also returns "default"if xis any falsy value, including an empty list, 0, empty string, or even datetime.time(0)(midnight).
请注意,这也会返回"default"ifx是任何虚假值,包括空列表、0、空字符串,甚至datetime.time(0)(午夜)。
回答by Ashwini Chaudhary
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
回答by Jon Clements
You've got the ternary syntax x if x else ''- is that what you're after?
您已经掌握了三元语法x if x else ''- 这就是您所追求的吗?
回答by brent.payne
return "default" if x is None else x
try the above.
试试上面的。
回答by zoigo
x or "default"
works best — i can even use a function call inline, without executing it twice or using extra variable:
效果最好——我什至可以使用内联函数调用,无需执行两次或使用额外的变量:
self.lineEdit_path.setText( self.getDir(basepath) or basepath )
I use it when opening Qt's dialog.getExistingDirectory()and canceling, which returns empty string.
我在打开 Qtdialog.getExistingDirectory()和取消时使用它,它返回空字符串。

