Python:将None转换为空字符串的最惯用方式? [英] Python: most idiomatic way to convert None to empty string?

查看:162
本文介绍了Python:将None转换为空字符串的最惯用方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行以下操作的最惯用的方法是什么?

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)

更新:我合并了Tryptich的建议使用str(一个或多个),这使该例程可用于字符串以外的其他类型.Vinay Sajip的lambda建议给我留下了深刻的印象,但我想保持我的代码相对简单.

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)

推荐答案

如果您实际上希望函数的行为类似于内置的 str(),但是当参数为无,请执行以下操作:

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)

这篇关于Python:将None转换为空字符串的最惯用方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆