将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] ...发布于 2009-08-27 02:16:42
a = line_parts[0] or "0"这是最好的Python习惯用法之一,使得提供默认值变得很容易。对于函数的默认值,它通常是这样使用的:
def fn(arg1, arg2=None):
arg2 = arg2 or ["weird default value"]发布于 2009-08-27 02:15:50
a = '0' if not line_parts[0] else line_parts[0]发布于 2018-09-27 16:12:07
如果您还希望将空格视为empty,并获得这些空格的剥离结果,下面的代码将会有所帮助。
a = (line_parts[0] and line_parts[0].strip()) or "0"https://stackoverflow.com/questions/1338518
复制相似问题