Python: most idiomatic way to convert None to empty string?
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.
def xstr(s):
return '' if s is None else str(s)
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)