Skip to main content

How to Replace None with Empty Strings or Integers in Python

In Python, you'll often encounter situations where a variable might be None, and you need to treat it as an empty string ("") or a zero (0) for further processing.

This guide explains how to safely and effectively replace None with these default values, using conditional expressions (the ternary operator) and the or operator.

Replacing None with an Empty String

The most explicit and readable way to replace None with an empty string is to use a conditional expression (also known as the ternary operator):

name = None
result = "" if name is None else str(name)
print(repr(result)) # Output: ''
  • "" if name is None else str(name): This reads as: "If name is None, then the result is ""; otherwise, the result is str(name)."
  • is None: Always use is or is not to check for None.
  • If you have to convert other type values into strings, you can use str(name).

Using the or Operator (Caution)

You can use the or operator, but be aware of its behavior:

name = None
result = name or ""
print(repr(result)) # Output: ''
  • name or "": The or operator returns the left operand if it's truthy; otherwise, it returns the right operand. Since None is falsy, the right operand ("") is returned.
  • Why the Caution? The or operator checks for falsiness, not just None. This means that if name were an empty string (""), the number zero (0), an empty list ([]), etc., the or operator would also return the empty string. If you only want to replace None and not any other falsy value, use is None instead of or.

Replacing None with an Integer (Zero)

my_var = None
result_1 = my_var or 0
print(result_1) # Output: 0

result_2 = my_var or 100
print(result_2) # Output: 100
  • The code uses the short-circuiting behaviour of the or operator to return 0 if the value is None.

Using the or Operator (Caution)

my_var = None
result = 0 if my_var is None else my_var
print(result) # Output: 0
  • The example uses the ternary operator to return 0 if the value is None, or the value if it is not None.

Creating Reusable Functions

For repeated use, create helper functions:

def convert_to_str(value):
return '' if value is None else str(value)

def convert_to_int(value):
return 0 if value is None else int(value)

print(convert_to_str(None)) # Output: ""
print(convert_to_str('tutorialreference.com')) # Output: 'tutorialreference.com'
print(convert_to_str(100)) # Output: 100
print(convert_to_int(None)) # Output: 0
print(convert_to_int(100)) # Output: 100
print(convert_to_int('500')) # Output: 500

  • These methods will receive a variable, and check if it is None. If it is it will return a default, otherwise it will convert it to the expected type.