How to Check if a String Is Empty in Python (Empty, Blank, None or NaN)

To check if a string is empty in Python, use if not s:. An empty string "" is “falsy”, so not s is True only when the string has no characters. If a string with only spaces should also count as empty, use if not s.strip():. This guide compares every way to check, and covers None, NaN values, pandas columns and lists of strings.

Every example was run with Python 3.12.5, NumPy 2.5.3 and pandas 3.0.6; the output shown is from those runs.

name = ""

if not name:
    print("The string is empty")

Output:

The string is empty

Three ways to check for an empty string

values = ["", "Python", " "]

for s in values:
    print(f"{s!r:10} not s: {not s!s:5}  s == '': {s == ''!s:5}  len(s) == 0: {len(s) == 0}")

Output:

''         not s: True   s == '': True   len(s) == 0: True
'Python'   not s: False  s == '': False  len(s) == 0: False
' '        not s: False  s == '': False  len(s) == 0: False
Command Prompt screenshot comparing not s, s == empty string and len(s) == 0 for an empty string, a word and a space in Python
The three checks run in the Command Prompt.
CheckEmpty string ""Spaces " "Notes
not sTrueFalseRecommended (PEP 8). Also True for None.
s == ""TrueFalseExplicit; False for None instead of an error.
len(s) == 0TrueFalseWorks, but raises TypeError for None.

All three treat " " as not empty: a space is a character. PEP 8, Python’s style guide, recommends if not s: because empty sequences are false.

Speed

import timeit

s = "Python"
for expr in ["not s", "s == ''", "len(s) == 0"]:
    t = min(timeit.repeat(expr, globals={"s": s}, number=2_000_000, repeat=5))
    print(f"{expr:12} {t / 2_000_000 * 1e9:5.1f} ns per check")

Output:

not s         14.4 ns per check
s == ''       17.7 ns per check
len(s) == 0   25.3 ns per check

The differences are a few nanoseconds per check (numbers from one run; yours will differ), so pick the one that reads best.

Check if a string is empty or only whitespace

values = ["", " ", "   ", "\t\n", "Python", "  Python  "]

for s in values:
    print(f"{s!r:14} empty: {not s!s:5}  blank (only spaces): {not s.strip()}")

Output:

''             empty: True   blank (only spaces): True
' '            empty: False  blank (only spaces): True
'   '          empty: False  blank (only spaces): True
'\t\n'         empty: False  blank (only spaces): True
'Python'       empty: False  blank (only spaces): False
'  Python  '   empty: False  blank (only spaces): False
Table comparing not s and not s.strip() for empty, space-only, tab-newline and non-empty Python strings
not s catches only ""; not s.strip() also catches spaces, tabs and newlines.

strip() removes spaces, tabs and newlines from both ends; if nothing is left, the string was blank. isspace() looks similar but returns False for the empty string:

for s in ["", " ", "\t\n", "a b"]:
    print(f"{s!r:8} isspace(): {s.isspace()}")

Output:

''       isspace(): False
' '      isspace(): True
'\t\n'   isspace(): True
'a b'    isspace(): False

Check if a string is not empty

username = "maria"

if username:                      # True for any non-empty string
    print(f"Hello, {username}!")

if username.strip():              # also rejects "   "
    print("Username is not blank")

Output:

Hello, maria!
Username is not blank

Example: validate user input

text = input("Enter some text: ")

if not text:
    print("You entered an empty string.")
elif not text.strip():
    print("You entered only spaces.")
else:
    print(f"You entered: {text.strip()!r}")
Command Prompt screenshot of a Python program where the user types only spaces and the program reports You entered only spaces
Real run: four spaces typed at the prompt are detected as a blank string.

Check if a string is None or empty

Python has no null; a missing value is usually None. Check is None first, because calling string methods on None fails:

def is_null_or_empty(s):
    """True for None, "" and strings that contain only whitespace."""
    return s is None or not s.strip()

for value in [None, "", "   ", "data"]:
    print(f"{value!r:8} -> {is_null_or_empty(value)}")

Output:

None     -> True
''       -> True
'   '    -> True
'data'   -> False
value = None
print(len(value))

Calling len() on None:

TypeError: object of type 'NoneType' has no len()

More on None and empty variables of any type: check if a variable is null or empty in Python.

Check if a string is empty or NaN

Data from CSV files and spreadsheets often contains NaN (a float) or the text "nan" instead of an empty string. pd.isna() recognises NaN, None and pd.NA, but not the text "nan":

import numpy as np
import pandas as pd

values = ["", "nan", "NaN", float("nan"), np.nan, None, pd.NA, "text"]

for v in values:
    print(f"{v!r:12} pd.isna: {pd.isna(v)!s:5}  empty or NaN: {pd.isna(v) or (isinstance(v, str) and not v.strip())}")

Output:

''           pd.isna: False  empty or NaN: True
'nan'        pd.isna: False  empty or NaN: False
'NaN'        pd.isna: False  empty or NaN: False
nan          pd.isna: True   empty or NaN: True
nan          pd.isna: True   empty or NaN: True
None         pd.isna: True   empty or NaN: True
<NA>         pd.isna: True   empty or NaN: True
'text'       pd.isna: False  empty or NaN: False

To treat blanks, None, NaN and the text “nan” the same way without pandas:

import math

def is_empty_or_nan(value):
    """Empty/blank string, None, a NaN float, or the text 'nan'."""
    if value is None:
        return True
    if isinstance(value, float):
        return math.isnan(value)
    if isinstance(value, str):
        return not value.strip() or value.strip().lower() == "nan"
    return False

for v in ["", "  ", "nan", "NaN", float("nan"), "0", 0.0, "Python"]:
    print(f"{v!r:10} -> {is_empty_or_nan(v)}")

Output:

''         -> True
'  '       -> True
'nan'      -> True
'NaN'      -> True
nan        -> True
'0'        -> False
0.0        -> False
'Python'   -> False
Command Prompt screenshot of a Python function that treats empty strings, blanks, None, NaN and the text nan as empty
The is_empty_or_nan() helper run in the Command Prompt.

Find empty strings in a pandas column

import numpy as np
import pandas as pd

df = pd.DataFrame({"name": ["Ann", "", "  ", None, np.nan, "Bob"]})

blank = df["name"].isna() | df["name"].str.strip().eq("")
print(df.assign(empty=blank))
print("\nrows with a real name:", df.loc[~blank, "name"].tolist())

Output:

  name  empty
0  Ann  False
1        True
2        True
3  NaN   True
4  NaN   True
5  Bob  False

rows with a real name: ['Ann', 'Bob']

Remove empty strings from a list

names = ["Ann", "", "Bob", "   ", "Cy"]

clean = [n for n in names if n.strip()]         # drop empty and blank strings
print(clean)
print("any empty?", any(not n.strip() for n in names))
print("all filled?", all(n.strip() for n in names))

Output:

['Ann', 'Bob', 'Cy']
any empty? True
all filled? False

Common mistakes

There is no isempty() method

s = ""
print(s.isempty())

Output:

AttributeError: 'str' object has no attribute 'isempty'

“” is falsy, but it is not False or None

print(bool(""), bool(" "), bool("0"), bool("False"))
print("" == False, "" is None)

Output:

False True True True
False False

bool("0") and bool("False") are True: any non-empty string is truthy, whatever it says.

Explore more string and variable checks:

Frequently asked questions

How do I check if a string is empty in Python?

Use if not s:. It is True for "" and False for any string with at least one character.

How do I check if a string is empty or contains only spaces?

Use if not s.strip():. strip() removes spaces, tabs and newlines, so a blank string becomes "".

How do I check if a string is not empty?

Use if s:, or if s.strip(): to also reject strings that only contain spaces.

Is there an isEmpty() method for strings in Python?

No. "".isempty() raises AttributeError. Use not s or len(s) == 0.

How do I check if a string is None or empty?

if s is None or not s.strip():. Check is None first so you never call a method on None.

Is an empty string False in Python?

It is falsy (bool("") is False), but "" == False is False and "" is None is False.