什么是用于将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] ...
a = line_parts[0] or "0"
这是最好的Python习语之一,可以很容易地提供默认值。对于函数的默认值,它通常像这样使用:
def fn(arg1, arg2=None):
arg2 = arg2 or ["weird default value"]
a = '0' if not line_parts[0] else line_parts[0]
如果您还想将白色空间视为empty
并获得结果剥离,下面的代码将有所帮助,
a = (line_parts[0] and line_parts[0].strip()) or "0"