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

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

    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 '')
    

提交回复
热议问题