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

前端 未结 16 1139
[愿得一人]
[愿得一人] 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:33

    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 '')
    
    0 讨论(0)
  • 2020-11-28 02:33

    Use F string if you are using python v3.7

    xstr = F"{s}"
    
    0 讨论(0)
  • 2020-11-28 02:37

    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) # -> ''
    
    0 讨论(0)
  • 2020-11-28 02:37

    Variation on the above if you need to be compatible with Python 2.4

    xstr = lambda s: s is not None and s or ''
    
    0 讨论(0)
  • 2020-11-28 02:38

    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)
    
    0 讨论(0)
  • 2020-11-28 02:38

    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.

    0 讨论(0)
提交回复
热议问题