Python – Transform None to Empty String (a 1 Liner)
Here you go:
lambda x: ['',x][int(bool(x))]
I got tired of constantly pasting this function in all my code:
def none2blank(val):
if val:return val
else:return ''
So I really wanted an expression that would do the same thing. Hopefully I’ve discovered it now. So I can use it like this:
print some_function_that_MUST_have_a_string(['',x][int(bool(x))])
Go enjoy it, or alternatively tell me why it won’t work, or why I shouldn’t need this. All feedback is welcome.
For this situation (where x is a string or None), I use :
x or ”
Which (assuming I understand correctly) does the same as your code but is much more readable…
def none2blank(val):
if val:return val
else:return ''
print none2blank(val)
Is equivalent to:
print val or ''
It seems that the way “or” works is that it will return the second value if both are bool() to False, but the first value if both bool() to True.
Hmm, x or ” is quite smart! Why didn’t I think of that? Thanks for the tip.
I guess that isn’t depending on an implementation detail/decision that might change, right? ah well, I’ll take a chance.
No, this isn’t an implementation detail. It is short circuiting of expressions which is very much a reliable feature.
It is the same mechanism that allows you to do:
if hasattr(x, ’something’) and x.something():
You can guarantee (because of short circuting) that if x doesn’t have the ’something’ method then it won’t get called.
Fuzzy
>>> [0,1][bool(None)]
0
>>> [0,1][int(bool(None))]
0
>>> [0,1][False]
0
In other words, you don’t need the int()
I’ve used the
[y, x][bool(expr)]construct a few times. (Aside: I don’t think the int conversion is necessary.)It’s usually confusing because the default choice comes second if you want bool to be True (which seems natural to me). Also, you have to manually convert expr to bool.
I was just thinking “Can the
x or ystyle replace the[y, x][b]style in general?” It can’t, because (in 2.5-speak):x or y=>x if x else y[y, x][b]=>x if b else yWyatt, said:
> x or y => x if x else y
> [y, x][b] => x if b else y
But doesn’t:
b == x
Therefore they do work in the same way?
- Paddy.
@Paddy
> But doesn’t: b == x
In
[y, x][b],brepresentsbool(e), whereeis some arbitrary expression.