Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you change a None to an empty string in Python?

Use the boolean OR operator to convert None to an empty string in Python, e.g. result = None or "" . The boolean OR operator returns the value to the left if it's truthy, otherwise the value to the right is returned. Since None is a falsy value, the operation will return "" . Copied!

How do you return an empty string in Python?

Use len to Check if a String in Empty in Python # Using len() To Check if a String is Empty string = '' if len(string) == 0: print("Empty string!") else: print("Not empty string!") # Returns # Empty string!

Does None equal empty string Python?

The None value is not an empty string in Python, and neither is (spaces).

Is None equal to empty string?

None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.


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.


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

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)

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

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


def xstr(s):
   return s or ""

Functional way (one-liner)

xstr = lambda s: '' if s is None else s