The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Over Ancient Waters Looping

--

Chapters
00:00 Question
00:43 Accepted answer (Score 114)
01:02 Answer 2 (Score 209)
01:25 Answer 3 (Score 168)
01:35 Answer 4 (Score 104)
01:52 Thank you

--

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

Answer 1 links:
[Boolean Operators]: http://docs.python.org/library/stdtypes....

--

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!