The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping

--

Chapters
00:00 Python: Most Idiomatic Way To Convert None To Empty String?
00:30 Answer 1 Score 176
00:37 Accepted Answer Score 118
00:52 Answer 3 Score 108
01:05 Answer 4 Score 70
01:12 Thank you

--

Full question
https://stackoverflow.com/questions/1034...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#string #python #idioms

#avk47



ANSWER 1

Score 176


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



ACCEPTED ANSWER

Score 118


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)



ANSWER 3

Score 108


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) # -> ''



ANSWER 4

Score 70


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