Last updated: Jun 15, 2022
Photo from Unsplash
Use the boolean OR operator to convert NoneType to a string in Python, e.g.
result = None or "". The boolean OR operator will return the value to the
right-hand side because the value to the left (
None) is falsy.
my_var = None result_1 = my_var or '' print(result_1) # 👉️ "" result_2 = my_var or 'hello' print(result_2) # 👉️ "hello"
We used the boolean or operator to return a string if the value to the left is falsy.
All values that are not truthy are considered falsy. The falsy values in Python are:
0(zero) of any numeric type
x or yreturns the value to the left if it's truthy, otherwise the value to the right is returned.
None is a falsy value, the expression
None or y is always going to
x or ywould also return
xis any of the other falsy values, e.g.
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 a string.
country = None if country is None: country = "" print(country) # 👉️ ""
None is much more explicit and the
if block will only run if
the variable stores a
The condition wouldn't be satisfied if the variable stores any other falsy value.
You can also use a one-liner
country = None country = "" if country is None else country print(country) # 👉️ ""
If the variable stores
None, it gets set to an empty string, otherwise it gets
set to its current value.
country = 'Germany' country = "" if country is None else country print(country) # 👉️ "Germany"