Check if a String is Empty in Python



The strings are the fundamental data types that are used to store text. When working with the string, Checking if the string is empty or not is a common task.

An empty string is nothing but the string with zero characters. There are various to check if a sting is empty, But choosing the elegant ways helps to improve the code readability. Let's dive into the article to learn more about it.

Using if not my_string

In Python, empty strings are considered as falsy, Which evaluates to false in a boolean content. So using not my_string returns true if the string is empty.

Example

Let's look at the following example, where we are going to use the basic way to check whether the string is empty or not.

str1 = ""
if not str1:
    print("It Is Empty.")
else:
    print("It Is Not Empty.")

The output of the above program is as follows -

The string is empty.

Using Python len() Function

The Python len() function is used to determine the length of an object (such as list, string or dictionary). We are going to apply this function to the string to return the number of characters, if the string is empty it returns true, otherwise false.

The Python len() function works only on the objects that are considered as collections.

Syntax

Following is the syntax for the Python len() function -

string.encode(encoding=encoding, errors=errors)

Example

Consider the following example, where we are going to check whether the string is empty or not using the len() function.

str1 = ""
if len(str1) == 0:
    print("It Is Empty!")
else:
    print("It Is Not Empty.")

The output of the above program is as follows -

It Is Empty!

Using Equality Comparison

This is another approach, where we are going to perform the Equality Comparison, to check whether the variable is exactly equal to an empty string literal "".

Example

In the following example, we are going to check whether the string is empty or not by using the equality comparison.

x = ""
if x == "":
    print("The string is empty.")
else:
    print("It Is Not Empty.")

The following is the output of the above program -

The string is empty.

Using Python strip() Method

The Python strip() method is used to remove all the specified leading and trailing characters from the beginning and end of the string.

In this approach, we are going to use the string, which contains the whitespace, which is not empty, and apply this method to remove the whitespace characters from the string, making the string falsy.

Syntax

Following is the syntax for the Python strip() function -

str.strip(characters)

Example

Following is the example, where we are going to use the strip() method.

str1 = "   "
if not str1.strip():
    print("It Is Empty.")
else:
    print("It Is Not Empty.")

The output of the above program is as follows -

It Is Empty.
Updated on: 2025-04-21T15:54:00+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements