Python check null or empty

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.

Python strings are immutable and hence have more complex handling when talking about its operations. Note that a string with spaces is actually an empty string but has a non-zero size. This article also discussed that problem and solution to it. 
Let’s see different methods of checking if string is empty or not.

Method #1 : Using len() 

Using len() is the most generic method to check for zero-length string. Even though it ignores the fact that a string with just spaces also should be practically considered as empty string even its non zero.

Python3

test_str1 = ""

test_str2 = "  "

print("The zero length string without spaces is empty ? : ", end="")

if(len(test_str1) == 0):

    print("Yes")

else:

    print("No")

print("The zero length string with just spaces is empty ? : ", end="")

if(len(test_str2) == 0):

    print("Yes")

else:

    print("No")

Output : 
 

The zero length string without spaces is empty ? : Yes
The zero length string with just spaces is empty ? : No

Method #2 : Using not 

not operator can also perform the task similar to len(), and checks for 0 length string, but same as the above, it considers the string with just spaces also to be non-empty, which should not practically be true.  

Python3

test_str1 = ""

test_str2 = "  "

print ("The zero length string without spaces is empty ? : ", end = "")

if(not test_str1):

    print ("Yes")

else :

    print ("No")

print ("The zero length string with just spaces is empty ? : ", end = "")

if(not test_str2):

    print ("Yes")

else :

    print ("No")

Output :  

The zero length string without spaces is empty ? : Yes
The zero length string with just spaces is empty ? : No

Method #3 : Using not + str.strip() 

The problem of empty + zero length string can be possibly be removed by using strip(), strip() returns true if it encounters the spaces, hence checking for it can solve the problem of checking for a purely empty string. 
 

Python3

test_str1 = ""

test_str2 = "  "

print ("The zero length string without spaces is empty ? : ", end = "")

if(not (test_str1 and test_str1.strip())):

    print ("Yes")

else :

    print ("No")

print ("The zero length string with just spaces is empty ? : ", end = "")

if(not(test_str2 and test_str2.strip())):

    print ("Yes")

else :

    print ("No")

Output:  

The zero length string without spaces is empty ? : Yes
The zero length string with just spaces is empty ? : Yes

Method #4 : Using not + str.isspace 

Works in similar way as the above method, and checks for spaces in the string. This method is more efficient because, strip() requires to perform the strip operation also which takes computation loads, if no. of spaces are of good number.

Python3

test_str1 = ""

test_str2 = "  "

print ("The zero length string without spaces is empty ? : ", end = "")

if(not (test_str1 and not test_str1.isspace())):

    print ("Yes")

else :

    print ("No")

print ("The zero length string with just spaces is empty ? : ", end = "")

if(not (test_str2 and not test_str2.isspace())):

    print ("Yes")

else :

    print ("No")

Output : 
 

The zero length string without spaces is empty ? : Yes
The zero length string with just spaces is empty ? : Yes

Method: Using list comprehension 

Python3

string=""

x=["no" if len(string)>0 else "yes"]

print(x)


How do you check if a value is empty or null 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!

How do you check for null in Python?

Use the is operator to check if a variable is null in Python, e.g. if my_var is None: . The is operator returns True if the values on the left-hand and right-hand sides point to the same object and should be used when checking for singletons like None .

Is None or empty Python?

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

How do I check if a string is empty or null?

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.