Skip to content

How to Check If a String Is Not Empty in Python

Learn the Pythonic way to verify non-empty strings using boolean evaluation, handle whitespace-only cases with .strip(), and safely check for None values.

In Python, checking whether a string contains data is a frequent operation, used for validating user input, parsing files, and managing control flow. There are two primary ways to do this: the "Pythonic" boolean evaluation and the explicit length check.

This guide explains both methods and clarifies how Python handles spaces and None values.

In Python, empty strings "" are "Falsy" (evaluate to False). Any string containing at least one character is "Truthy" (evaluates to True). This allows for concise code.

Syntax:

text = "Hello"

if text:
    print("String is not empty.")
else:
    print("String is empty.")

Output:

String is not empty.

Method 2: Using len() (Explicit)

You can check if the length of the string is greater than 0. While functionally identical to Method 1, it is more verbose. It is useful if you specifically need the length for other logic.

text = ""

if len(text) > 0:
    print("String has content.")
else:
    print("String is empty.")

Output:

String is empty.

Edge Case: Strings with Spaces Only

A string containing spaces " " is not empty. It has a length greater than 0 and evaluates to True.

If you consider a string of only whitespace to be "empty" (e.g., in a form field), you must use .strip() before checking.

blank_text = "   "

if blank_text:
    print("Standard check: Not Empty (Contains spaces)")

if blank_text.strip():
    print("Strip check: Not Empty")
else:
    print("Strip check: Empty (Only whitespace)")

Output:

Standard check: Not Empty (Contains spaces)
Strip check: Empty (Only whitespace)

Edge Case: Handling None

A variable might be None instead of a string. None evaluates to False, so if text: handles both None and "" safely. However, len(text) will crash if text is None.

data = None

if data:
    print("Data exists.")
else:
    print("Data is None or Empty.")

Output:

Data is None or Empty.

Conclusion

To check if a string is not empty:

  1. Use if my_string: for the standard, clean check.
  2. Use if my_string.strip(): if you want to treat strings with only spaces as empty.
  3. Avoid len() unless you specifically need the character count.
Navigation