Check for an empty or whitespace-only string in Python

Distinguish empty strings, whitespace, and None in Python, and choose an input check that matches the types your application accepts.

Best practices
Python programming and application logging

For a value known to be a string, if not text: checks whether it is empty. Use if not text.strip(): if whitespace-only input should count as empty too.

Empty and blank are different

text = ""
if not text:
    print("Empty string")

text = "  \t\n"
if not text.strip():
    print("Empty or whitespace-only string")

text == "" is also valid and explicitly tests equality with an empty string. By contrast, not text is a general truth-value test: it also matches None, 0, and empty containers.

Treat missing values separately

For a function accepting a string or None, make the distinction explicit:

def classify(text):
    if text is None:
        return "Missing"
    if not isinstance(text, str):
        raise TypeError("Expected a string or None")
    if text == "":
        return "Empty"
    if not text.strip():
        return "Whitespace only"
    return "Has content"

This avoids calling .strip() on None and prevents other false values from being silently accepted as strings.

FAQ

Does strip() change the original string? No. Strings are immutable. It returns the trimmed result; assign that result if you want to use it later.

What should I use for a form field? If the field is guaranteed to be a string or None, if not (text and text.strip()): rejects missing, empty, and blank values. When input types are uncertain, validate the type first, as above.

Does trimming remove every invisible character? No. strip() without an argument removes characters Python classifies as whitespace at the ends. It does not remove every invisible Unicode character or replace field-specific validation.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting