Skip to content
Home / Fundamentals

Checking if a string is empty in Python

In Python, a string is considered empty if it is either None or if its length is zero. There are several ways to check if a string is empty in Python.

Method 1: Using the len() function

The len() function returns the length of a string, which can be used to check if the string is empty. An empty string has a length of 0, so if the length of the string is 0, it is considered empty.

Here is an example:

string = ""

if len(string) == 0:
    print("The string is empty")
else:
    print("The string is not empty")

This will print "The string is empty", because the length of the empty string is 0.

Method 2: Using the not operator

Another way to check if a string is empty is to use the not operator. The not operator negates a boolean value, so if a string is empty, not string will evaluate to True.

Here is an example:

string = ""

if not string:
    print("The string is empty")
else:
    print("The string is not empty")

This will also print "The string is empty", because not "" evaluates to True.

Method 3: Using the isspace() function

If you want to check if a string consists only of whitespace characters, you can use the isspace() function. This function returns True if the string consists only of whitespace characters (such as spaces, tabs, or newlines).

Here is an example:

string = "   \t\n"

if string.isspace():
    print("The string is empty")
else:
    print("The string is not empty")

This will print "The string is empty", because the string consists only of whitespace characters.