Python:将None转换为空字符串的最常用的方法是什么?

Python: most idiomatic way to convert None to empty string?

做以下事情的最惯用方法是什么?

1
2
3
4
5
6
7
def xstr(s):
    if s is None:
        return ''
    else:
        return s

s = xstr(a) + xstr(b)

更新:我正在使用Tryptich的建议来使用str(s),这使得这个例程适用于除字符串之外的其他类型。 Vinay Sajip的lambda建议给我留下了深刻的印象,但我希望保持我的代码相对简单。

1
2
3
4
5
def xstr(s):
    if s is None:
        return ''
    else:
        return str(s)


1
2
def xstr(s):
    return '' if s is None else str(s)


如果您知道该值将始终为字符串或None:

1
2
3
4
5
6
xstr = lambda s: s or""

print xstr("a") + xstr("b") # -> 'ab'
print xstr("a") + xstr(None) # -> 'a'
print xstr(None) + xstr("b") # -> 'b'
print xstr(None) + xstr(None) # -> ''


如果您确实希望函数的行为类似于str()内置函数,但在参数为None时返回空字符串,请执行以下操作:

1
2
3
4
def xstr(s):
    if s is None:
        return ''
    return str(s)


可能是最短的
str(s or '')

因为None是False,如果x是false,"x或y"返回y。有关详细说明,请参阅布尔运算符。这很简短,但不是很明确。


return s or ''可以很好地解决您所说的问题!


1
2
def xstr(s):
   return s or""


功能方式(单线)

1
xstr = lambda s: '' if s is None else s


1
2
def xstr(s):
    return {None:''}.get(s, s)


在一些其他答案的基础上做一个整洁的单行:

1
s = (lambda v: v or '')(a) + (lambda v: v or '')(b)

甚至只是:

1
s = (a or '') + (b or '')


我使用max函数:

1
2
max(None, '')  #Returns blank
max("Hello",'') #Returns Hello

像魅力一样工作;)只需将您的字符串放在函数的第一个参数中。


如果您需要与Python 2.4兼容,请修改上述内容

1
xstr = lambda s: s is not None and s or ''


如果只是格式化字符串,您可以执行以下操作:

1
2
3
4
5
6
7
8
9
from string import Formatter

class NoneAsEmptyFormatter(Formatter):
    def get_value(self, key, args, kwargs):
        v = super().get_value(key, args, kwargs)
        return '' if v is None else v

fmt = NoneAsEmptyFormatter()
s = fmt.format('{}{}', a, b)

在下面解释的场景中,我们总是可以避免类型转换

1
2
3
4
5
6
customer ="John"
name = str(customer)
if name is None
   print"Name is blank"
else:
   print"Customer name :" + name

在上面的示例中,如果变量customer的值为None,则在分配给'name'时它会进一步转换。 'if'子句中的比较总是会失败。

1
2
3
4
5
6
customer ="John" # even though its None still it will work properly.
name = customer
if name is None
   print"Name is blank"
else:
   print"Customer name :" + str(name)

以上示例将正常工作。当从URL,JSON或XML获取值时,这种情况非常常见,甚至值也需要进行任何操作的进一步类型转换。


1
2
3
4
def xstr(s):
    return s if s else ''

s ="%s%s" % (xstr(a), xstr(b))


使用短路评估:

1
s = a or '' + b or ''

由于+对字符串不是很好的操作,因此最好使用格式字符串:

1
s ="%s%s" % (a or '', b or '')