单行Python代码,用于将字符串设置为0字符串(如果为空)

问题描述 投票:19回答:3

什么是用于将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] ...
python string
3个回答
71
投票
a = line_parts[0] or "0"

这是最好的Python习语之一,可以很容易地提供默认值。对于函数的默认值,它通常像这样使用:

def fn(arg1, arg2=None):
    arg2 = arg2 or ["weird default value"]

12
投票
a = '0' if not line_parts[0] else line_parts[0]

0
投票

如果您还想将白色空间视为empty并获得结果剥离,下面的代码将有所帮助,

a = (line_parts[0] and line_parts[0].strip()) or "0"
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.