Python: most idiomatic way to convert None to empty string?

Posted on

Question :

Python: most idiomatic way to convert None to empty string?

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)

update: I’m incorporating Tryptich’s suggestion to use str(s), which makes this routine work for other types besides strings. I’m awfully impressed by Vinay Sajip’s lambda suggestion, but I want to keep my code relatively simple.

def xstr(s):
    if s is None:
        return ''
    else:
        return str(s)

Answer #1:

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)
Answered By: Mark Harrison

Answer #2:

def xstr(s):
    return '' if s is None else str(s)
Answered By: Triptych

Answer #3:

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.

Answered By: SilentGhost

Answer #4:

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) # -> ''
Answered By: dorvak

Answer #5:

return s or '' will work just fine for your stated problem!

Answered By: Vinay Sajip

Answer #6:

def xstr(s):
   return s or ""
Answered By: Alex Martelli

Answer #7:

Functional way (one-liner)

xstr = lambda s: '' if s is None else s
Answered By: Krystian Cybulski

Answer #8:

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 '')
Answered By: Dario

Leave a Reply

Your email address will not be published. Required fields are marked *