用于将字符串设置为 0 字符串(如果为空)的单行 Python 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1338518/
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
One-liner Python code for setting string to 0 string if empty
提问by biznez
What is a one-liner code for setting a string in python to the string, 0 if the string is empty?
什么是在python中将字符串设置为字符串的单行代码,如果字符串为空则为0?
# line_parts[0] can be empty
# if so, set a to the string, 0
# one-liner solution should be part of the following line of code if possible
a = line_parts[0] ...
回答by Ned Batchelder
a = line_parts[0] or "0"
This is one of the nicest Python idioms, making it easy to provide default values. It's often used like this for default values of functions:
这是最好的 Python 习惯用法之一,可以轻松提供默认值。它通常像这样用于函数的默认值:
def fn(arg1, arg2=None):
arg2 = arg2 or ["weird default value"]
回答by Andrew Keeton
a = '0' if not line_parts[0] else line_parts[0]
回答by Kannan Ramamoorthy
If you would also like to consider the white spaces as empty
and get the result stripping of those, the below code will help,
如果您还想将空格视为empty
并获得删除这些空格的结果,以下代码将有所帮助,
a = (line_parts[0] and line_parts[0].strip()) or "0"