Check if a String is Empty in Python

The easiest way to check whether the string is empty is to use the len function. This function is going to return the length of a string.

If there are no characters, it returns 0.

0

Calling method directly

The len function from the previous example calls implicitly the __len__() method. We can also call this method directly from the object.

This code also returns 0.

Using the “not” keyword

In the previous examples, the string is empty if the result is 0. In this example, we are going to use the boolean type to return True if the string is empty.

This code prints True as a result.

If you want the function to return False, you can’t just remove the not keyword because it’s going to print variable contents, which in our case is ”. You can do it by using the bool function.

This code is going to return True.

We can modify this to display a message informing us whether the string is empty or not.

This code prints this message on the console.

String is empty

The equation operator (=)

The fourth way to check the string is to use the equation sign. In this case, we are going to check whether the string equals an empty string.

The result of this code is the same as before.

What is an empty string?

We treated “” as an empty string. All the previous examples have worked well so far. But you can also treat ” “, or ”    ” as an empty string.

To deal with this problem, you can use the strip() method.

These are the results.

3
0
False
True