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

前端 未结 16 1140
[愿得一人]
[愿得一人] 2020-11-28 02:21

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)


        
相关标签:
16条回答
  • 2020-11-28 02:50

    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)
    
    0 讨论(0)
  • 2020-11-28 02:51
    def xstr(s):
        return s if s else ''
    
    s = "%s%s" % (xstr(a), xstr(b))
    
    0 讨论(0)
  • 2020-11-28 02:58
    def xstr(s):
       return s or ""
    
    0 讨论(0)
  • 2020-11-28 02:58

    Functional way (one-liner)

    xstr = lambda s: '' if s is None else s
    
    0 讨论(0)
提交回复
热议问题