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)
Use short circuit evaluation:
s = a or '' + b or ''
Since + is not a very good operation on strings, better use format strings:
s = "%s%s" % (a or '', b or '')
Use F string if you are using python v3.7
xstr = F"{s}"
If you know that the value will always either be a string or None:
xstr = lambda s: s or ""
print xstr("a") + xstr("b") # -> 'ab'
print xstr("a") + xstr(None) # -> 'a'
print xstr(None) + xstr("b") # -> 'b'
print xstr(None) + xstr(None) # -> ''
Variation on the above if you need to be compatible with Python 2.4
xstr = lambda s: s is not None and s or ''
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)
I use max function:
max(None, '') #Returns blank
max("Hello",'') #Returns Hello
Works like a charm ;) Just put your string in the first parameter of the function.