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

Mark Harrison picture Mark Harrison · Jun 23, 2009 · Viewed 194.8k times · Source

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)

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)

Answer

SilentGhost picture SilentGhost · Jun 23, 2009
def xstr(s):
    return '' if s is None else str(s)