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


Question

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)
1
133
7/21/2009 3:17:00 AM

Accepted Answer

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)
84
6/23/2009 7:28:18 PM

def xstr(s):
    return '' if s is None else str(s)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon