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)
def xstr(s):
return {None:''}.get(s, s)
We can always avoid type casting in scenarios explained below.
customer = "John"
name = str(customer)
if name is None
print "Name is blank"
else:
print "Customer name : " + name
In the example above in case variable customer's value is None the it further gets casting while getting assigned to 'name'. The comparison in 'if' clause will always fail.
customer = "John" # even though its None still it will work properly.
name = customer
if name is None
print "Name is blank"
else:
print "Customer name : " + str(name)
Above example will work properly. Such scenarios are very common when values are being fetched from URL, JSON or XML or even values need further type casting for any manipulation.
return s or ''
will work just fine for your stated problem!
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.
A neat one-liner to do this building on some of the other answers:
s = (lambda v: v or '')(a) + (lambda v: v or '')(b)
or even just:
s = (a or '') + (b or '')