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

前端 未结 16 1315
[愿得一人]
[愿得一人] 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: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) # -> ''
    

提交回复
热议问题