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

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


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


Probably the shortest would be str(s or '')

Because None is False, and "x or y" returns y if x is false. See Boolean Operators for a detailed explanation. It's short, but not very explicit.


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)