一行Python代码将空字符串设置为"0"字符串
在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] ...
3 个回答
0
如果你想把空格也当作空
来处理,并且希望结果中去掉这些空格,下面的代码可以帮到你。
a = (line_parts[0] and line_parts[0].strip()) or "0"
13
a = '0' if not line_parts[0] else line_parts[0]
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
89
a = line_parts[0] or "0"
这是Python中一个非常好用的写法,它让我们很方便地设置默认值。通常在定义函数的时候,会这样使用默认值:
def fn(arg1, arg2=None):
arg2 = arg2 or ["weird default value"]