问题:Python:将None转换为空字符串的最惯用方式?
做以下事情的最惯用的方法是什么?
def xstr(s):
if s is None:
return ''
else:
return s
s = xstr(a) + xstr(b)
更新:我合并了Tryptich的建议使用str(s),这使此例程可用于字符串以外的其他类型。Vinay Sajip的lambda建议给我留下了深刻的印象,但是我想保持我的代码相对简单。
def xstr(s):
if s is None:
return ''
else:
return str(s)
What is the most idiomatic way to do the following?
def xstr(s):
if s is None:
return ''
else:
return s
s = xstr(a) + xstr(b)
update: I’m incorporating Tryptich’s suggestion to use str(s), which makes this routine work for other types besides strings. I’m awfully impressed by Vinay Sajip’s lambda suggestion, but I want to keep my code relatively simple.
def xstr(s):
if s is None:
return ''
else:
return str(s)
回答 0
如果您实际上希望函数的行为类似于str()
内置函数,但是当参数为None时返回空字符串,请执行以下操作:
def xstr(s):
if s is None:
return ''
return str(s)
If you actually want your function to behave like the str()
built-in, but return an empty string when the argument is None, do this:
def xstr(s):
if s is None:
return ''
return str(s)
回答 1
def xstr(s):
return '' if s is None else str(s)
def xstr(s):
return '' if s is None else str(s)
回答 2
可能最短的是
str(s or '')
因为None为False,如果x为false,则“ x或y”返回y。有关详细说明,请参见布尔运算符。它很短,但不是很明确。
Probably the shortest would be
str(s or '')
Because None is False, and “x or y” returns y if x is false. See Boolean Operators for a detailed explanation. It’s short, but not very explicit.
回答 3
如果您知道该值将始终是字符串或无:
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) # -> ''
If you know that the value will always either be a string or None:
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) # -> ''
回答 4
return s or ''
可以很好地解决您所说的问题!
return s or ''
will work just fine for your stated problem!
回答 5
def xstr(s):
return s or ""
def xstr(s):
return s or ""
回答 6
功能方式(单线)
xstr = lambda s: '' if s is None else s
Functional way (one-liner)
xstr = lambda s: '' if s is None else s
回答 7
一个巧妙的单线代码可以在其他一些答案上进行构建:
s = (lambda v: v or '')(a) + (lambda v: v or '')(b)
甚至只是:
s = (a or '') + (b or '')
A neat one-liner to do this building on some of the other answers:
s = (lambda v: v or '')(a) + (lambda v: v or '')(b)
or even just:
s = (a or '') + (b or '')
回答 8
def xstr(s):
return {None:''}.get(s, s)
def xstr(s):
return {None:''}.get(s, s)
回答 9
我使用max函数:
max(None, '') #Returns blank
max("Hello",'') #Returns Hello
就像一个吊饰;)只需将字符串放在函数的第一个参数中即可。
I use max function:
max(None, '') #Returns blank
max("Hello",'') #Returns Hello
Works like a charm ;) Just put your string in the first parameter of the function.
回答 10
如果您需要与Python 2.4兼容,请在上面进行修改
xstr = lambda s: s is not None and s or ''
Variation on the above if you need to be compatible with Python 2.4
xstr = lambda s: s is not None and s or ''
回答 11
如果要格式化字符串,则可以执行以下操作:
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)
If it is about formatting strings, you can do the following:
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)
回答 12
def xstr(s):
return s if s else ''
s = "%s%s" % (xstr(a), xstr(b))
def xstr(s):
return s if s else ''
s = "%s%s" % (xstr(a), xstr(b))
回答 13
在下面说明的场景中,我们总是可以避免类型转换。
customer = "John"
name = str(customer)
if name is None
print "Name is blank"
else:
print "Customer name : " + name
在上面的示例中,如果变量customer的值为None,则在分配给’name’的同时进一步进行强制转换。“ if”子句中的比较将始终失败。
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中获取值,甚至值需要进一步的类型转换以进行任何操作时,这种情况非常普遍。
We can always avoid type casting in scenarios explained below.
customer = "John"
name = str(customer)
if name is None
print "Name is blank"
else:
print "Customer name : " + name
In the example above in case variable customer’s value is None the it further gets casting while getting assigned to ‘name’. The comparison in ‘if’ clause will always fail.
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)
Above example will work properly. Such scenarios are very common when values are being fetched from URL, JSON or XML or even values need further type casting for any manipulation.
回答 14
使用短路评估:
s = a or '' + b or ''
由于+对字符串不是很好的操作,因此最好使用格式字符串:
s = "%s%s" % (a or '', b or '')
Use short circuit evaluation:
s = a or '' + b or ''
Since + is not a very good operation on strings, better use format strings:
s = "%s%s" % (a or '', b or '')
回答 15
如果使用的是python v3.7,请使用F字符串
xstr = F"{s}"
Use F string if you are using python v3.7
xstr = F"{s}"
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。