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)
If it is about formatting strings, you can do the following:
from string import Formatter
class NoneAsEmptyFormatter(Formatter):
def get_value(self, key, args, kwargs):
v = super().get_value(key, args, kwargs)
return '' if v is None else v
fmt = NoneAsEmptyFormatter()
s = fmt.format('{}{}', a, b)
def xstr(s):
return s if s else ''
s = "%s%s" % (xstr(a), xstr(b))
def xstr(s):
return s or ""
Functional way (one-liner)
xstr = lambda s: '' if s is None else s