Skip to main content

How to Check If a String Is Not Empty in Python

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"

# ✅ Correct: The Pythonic check
if text:
print("String is not empty.")
else:
print("String is empty.")

Output:

String is not empty.
tip

This method is preferred by PEP 8 guidelines because it is clean and readable.

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 = ""

# ✅ Correct: Explicit length check
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 = "   "

# ⛔️ Standard check says True (Not Empty)
if blank_text:
print("Standard check: Not Empty (Contains spaces)")

# ✅ Correct: Strip whitespace first
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

# ✅ Correct: Handles None safely
if data:
print("Data exists.")
else:
print("Data is None or Empty.")

# ⛔️ Incorrect: Crashes if data is None
# if len(data) > 0: ...

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.