How to convert None to an Empty string in Python

avatar

Borislav Hadzhiev

Last updated: Jun 15, 2022

banner

Photo from Unsplash

Convert 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 "".

main.py
name = None result = name or "" print(result) # 👉️ ""

We used the boolean or operator to return an empty string if the value to the left is falsy.

All values that are not truthy are considered falsy. The falsy values in Python are:

  • constants defined to be falsy: None and False.
  • 0 (zero) of any numeric type
  • empty sequences and collections: "" (empty string), () (empty tuple), [] (empty list), {} (empty dictionary), set() (empty set), range(0) (empty range).
The expression x or y 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 expression None or y is always going to return y.

Note that the expression x or y would also return y if x is any of the other falsy values, e.g. 0, False, or an empty list, dict or tuple.

Alternatively, you can use an if statement to check if the variable stores None and reassign it to an empty string.

main.py
name = None if name is None: name = "" print(name) # 👉️ ""

Checking for None is much more explicit and the if block will only run if the variable stores a None value.

The condition wouldn't be satisfied if the variable stores any other falsy value.

You can also use a one-liner if/else statement.

main.py
name = None name = "" if name is None else name print(name) # 👉️ ""

If the variable stores None, it gets set to an empty string, otherwise it gets set to its current value.

main.py
name = 'hello' name = "" if name is None else name print(name) # 👉️ "hello"
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.