Python: How to check if a string is empty

Updated: May 26, 2023 By: Goodman Post a comment

Python does not have built-in methods or attributes like is_empty() or is_empty specifically designed to check whether a string is empty. However, there are other ways to achieve the same result using the existing functionality of the programming language.

Using a boolean expression

In Python, an empty string is considered “falsy,” meaning it evaluates to False in a boolean context. Conversely, a non-empty string is considered “truthy” and evaluated as True. This allows you to directly use the string in boolean expressions to check if it’s empty or not.

Example:

text = ""

if text:
    print("Text is not empty")
else:
    print("Text is empty")

Output:

Text is empty

Using the len() function

Another way to know if a string is empty is to use the len() function:

  1. Use the len() function to get the length of the string.
  2. Check if the length of the string is equal to 0.
  3. Return True if the length is 0; otherwise, return False.

Example:

string_1 = "Sling Academy"
string_2 = ""

if len(string_1) == 0:
    print("String 1 is empty")
else:
    print("String 1 is not empty")

if len(string_2) == 0:
    print("String 2 is empty")
else:
    print("String 2 is not empty")

Output:

String 1 is not empty
String 2 is empty