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.

8 Responses to “Python – Transform None to Empty String (a 1 Liner)”

  1. Fuzzyman says:

    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…

  2. Brantley says:


    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.

  3. 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.

  4. Michael Foord says:

    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

  5. James Thiele says:

    >>> [0,1][bool(None)]
    0
    >>> [0,1][int(bool(None))]
    0
    >>> [0,1][False]
    0

    In other words, you don’t need the int()

  6. Wyatt says:

    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 y style 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 y

  7. Paddy3118 says:

    Wyatt, 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.

  8. Wyatt says:

    @Paddy

    > But doesn’t: b == x

    In [y, x][b], b represents bool(e), where e is some arbitrary expression.