How do you check if a value is empty or null in python?

I find hardcoding(sic) "" every time for checking an empty string not as good.

Clean code approach

Doing this: foo == "" is very bad practice. "" is a magical value. You should never check against magical values (more commonly known as magical numbers)

What you should do is compare to a descriptive variable name.

Descriptive variable names

One may think that "empty_string" is a descriptive variable name. It isn't.

Before you go and do empty_string = "" and think you have a great variable name to compare to. This is not what "descriptive variable name" means.

A good descriptive variable name is based on its context. You have to think about what the empty string is.

  • Where does it come from.
  • Why is it there.
  • Why do you need to check for it.

Simple form field example

You are building a form where a user can enter values. You want to check if the user wrote something or not.

A good variable name may be not_filled_in

This makes the code very readable

if formfields.name == not_filled_in:
    raise ValueError("We need your name")

Thorough CSV parsing example

You are parsing CSV files and want the empty string to be parsed as None

(Since CSV is entirely text based, it cannot represent None without using predefined keywords)

A good variable name may be CSV_NONE

This makes the code easy to change and adapt if you have a new CSV file that represents None with another string than ""

if csvfield == CSV_NONE:
    csvfield = None

There are no questions about if this piece of code is correct. It is pretty clear that it does what it should do.

Compare this to

if csvfield == EMPTY_STRING:
    csvfield = None

The first question here is, Why does the empty string deserve special treatment?

This would tell future coders that an empty string should always be considered as None.

This is because it mixes business logic (What CSV value should be None) with code implementation (What are we actually comparing to)

There needs to be a separation of concern between the two.

In this tutorial, we'll learn how to check if a variable if is empty by using 2 ways, the good and the bad ways.

1. Checking if variable is empty [Good way]

In this example, we'll check if the variable var is empty.


#empty variable
var = ""

#check if variable is empty
if not var:
    print("yes it is!")
    

output

yes it is!

as you can see, var is empty

2. Checking if variable is empty [Bad way]

In this example, we will do the same thing that we did in the first example, but now in the bad way.


#empty variable
var = ""

#check if variable is empty
if len(var) == 0:
    print("yes it is!")

    

output

yes it is!

As you can see, the code is working very well, but this is the worst way, because we don't need the len function,
remind, your code should be short, clean and easy to read

Conclusion

In this article, we have learned how to check empty variables, if you want to check empty variables, list and tuple, you should do like we did in the fist example.

The string data type in Python is immutable; that means you can not change a string once defined. A string with spaces is an empty string but has non-zero size. So, when you check the empty string with len() or not operator, it counts space as a character in the string, and hence it won’t count a string with space as an empty string.

The not operator in Python checks the string with just spaces to be non-empty, which should not practically be True.

Check if the strA is empty : The string is empty

The string is empty, and one thing to note is that we did not even put the space in the string. That is why it returns as empty. On the other hand, if we put a space in the string, it will not count as empty, and the not operator returns False.

# app.py

strA = " "

# checking if string with space is empty
print("Check if the strA with space is empty : ", end="")
if(not strA):
    print("The string is empty")
else:
    print("No it is not empty")

Output

Check if the strA with space is empty : No it is not empty

Using len() function

To check an empty string in Python, use the len() function; if it returns 0, that means the string is empty; otherwise, it is not.

So, if the string has something, it will count as a non-empty string; otherwise, it is an empty string.

strA = ""

# checking if string with space is empty
print("Check if the string is empty : ", end="")
if(len(strA)):
    print("The string is not empty")
else:
    print("The string is empty")

Output

Check if the string is empty : The string is empty

Here, if condition becomes False because it returns 0, that means else condition becomes True, and the string is empty.

If the string contains whitespace, it does not count as an empty string.

strA = " "

# checking if string with space is empty
print("Check if the string is empty : ", end="")
if(len(strA)):
    print("The string is not empty")
else:
    print("The string is empty")

Output

Check if the string is empty : The string is not empty

Space in string counts as a character. That is why when you check for the empty, it returns False.

Using len() + string.strip()

To check a pure empty string in Python, use len() + string.strip() method. The string.strip() method removes the whitespace from the string. So if it contains any space, the strip() function removes and checks if the string is empty or not using the len() function.

str = "   "

# checking if string with space is empty
print("Check if the string is empty : ", end="")
if(len(str.strip())):
    print("The string is not empty")
else:
    print("The string is empty")

Output

Check if the string is empty : The string is empty

Here, no matter how many spaces you will add to the string, it strips all the spaces and checks the length of the string, and if it returns 0, that means the string is empty; otherwise, not.

str = " KRUNAL  "

# checking if string with space is empty
print("Check if the string is empty : ", end="")
if(len(str.strip())):
    print("The string is not empty")
else:
    print("The string is empty")

Output

Check if the string is empty : The string is not empty

In this example, you can see that the string is not empty cause it has certain characters. So len() method returns the length of the string, and if the condition returns True.

Using not + string.isspace()

The string.isspace() function checks if the string contains any space or not. If the string contains any space, then it returns True. Otherwise, it returns False.

We use the combination of string and not string.isspace() method to check if the string is empty or not regardless of the space.

This method is more efficient than the strip() method because it requires executing the strip operation, which takes computation loading time if the string contains many spaces.

str = "  "

# checking if string with space is empty
print("Check if the string is empty : ", end="")
if(str and not str.isspace()):
    print("The string is not empty")
else:
    print("The string is empty")

Output

Check if the string is empty : The string is empty

Here, we are checking the negative condition of the isspace() function with and operator. 

If one of the conditions becomes False, then due to an “and operator” if condition returns False, the condition will be executed.

This is the better way to check a pure empty string in Python.

That is it for this tutorial.

See also

How to trim whitespace from a string

Python String startswith()

Python String endswith()

How do you know if its null or empty?

You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.

How do you check if a variable has no value in Python?

Use bool() to check if a variable is empty Call bool(o) with o set as a variable to check if the variable contains an empty value.

How do I check if a Python input is empty?

Use an if statement to check if a user input is empty, e.g. if country == '': . The input() function is guaranteed to return a string, so if it returns an empty string, the user didn't enter a value.

How do you check if a value is empty?

The IS NULL operator is used to test for empty values (NULL values).