将 None 转换为空字符串的最惯用方法?

发布于 2024-07-25 11:27:13 字数 1708 浏览 2 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

梦幻之岛 2024-08-01 11:27:13

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

因为 None 为 False,如果 x 为 false,则“x or 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.

聽兲甴掵 2024-08-01 11:27:13
def xstr(s):
    return '' if s is None else str(s)
def xstr(s):
    return '' if s is None else str(s)
风吹过旳痕迹 2024-08-01 11:27:13

如果您确实希望函数的行为类似于 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)
甲如呢乙后呢 2024-08-01 11:27:13

如果您知道该值始终是字符串或 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) # -> ''

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) # -> ''
鸩远一方 2024-08-01 11:27:13

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

return s or '' will work just fine for your stated problem!

污味仙女 2024-08-01 11:27:13
def xstr(s):
   return s or ""
def xstr(s):
   return s or ""
冷默言语 2024-08-01 11:27:13

更新:

我现在主要使用这个方法:

some_string = None
some_string or ''

如果 some_string 不是 NoneType,则 or 会短路并返回它,否则返回空字符串。

旧:

Max 函数在 python 2.x 中有效,但在 3.x 中无效:

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

UPDATE:

I mainly use this method now:

some_string = None
some_string or ''

If some_string was not NoneType, the or would short circuit there and return it, otherwise it returns the empty string.

OLD:

Max function worked in python 2.x but not in 3.x:

max(None, '')  # Returns blank
max("Hello", '') # Returns Hello
早茶月光 2024-08-01 11:27:13

功能方式(单行)

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

Functional way (one-liner)

xstr = lambda s: '' if s is None else s
万劫不复 2024-08-01 11:27:13

在其他一些答案的基础上做这件事的简洁的一句台词:

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 '')
酒与心事 2024-08-01 11:27:13
def xstr(s):
    return {None:''}.get(s, s)
def xstr(s):
    return {None:''}.get(s, s)
热血少△年 2024-08-01 11:27:13

如果您需要与 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 ''
左岸枫 2024-08-01 11:27:13

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

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)
屋檐 2024-08-01 11:27:13
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))
羁绊已千年 2024-08-01 11:27: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.

坚持沉默 2024-08-01 11:27:13

使用短路评估:

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 '')
神经大条 2024-08-01 11:27:13

与 Vinay Sajip 的答案相同,带有类型注释,这消除了对 str() 结果的需要。

def xstr(s: Optional[str]) -> str:
    return '' if s is None else s

Same as Vinay Sajip's answer with type annotations, which precludes the needs to str() the result.

def xstr(s: Optional[str]) -> str:
    return '' if s is None else s
对岸观火 2024-08-01 11:27:13

如果您使用的是 python v3.7,请使用 F 字符串

xstr = F"{s}"

Use F string if you are using python v3.7

xstr = F"{s}"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文