String method

str.isspace()

Returns True when a string is not empty and holds only whitespace: spaces, tabs, new lines and similar blank characters.

BeginnerEvery example below runs in your browser. Change the code and press Run.

str.isspace()

isspace() returns True if the string has at least one character and all of them are whitespace: spaces, tabs (\t), new lines (\n) and other blank characters.

Its typical use is spotting blank lines in a file, or input that only looks filled in.

An empty string gives False, which surprises people who want to test "is it blank?". For that, not text.strip() covers both empty and whitespace-only text.

Return value

True or False.

Examples

1Simple checks

Pythoneditable
print("   ".isspace())
print("\t\n".isspace())
print(" a ".isspace())
print("".isspace())
Output
True
True
False
False

2Skip blank lines in a file

Pythoneditable
with open("list.txt") as f:
    for line in f:
        if line.isspace():
            continue
        print(line.rstrip())
Output
apples
pears
plums

3Is a form field really filled in?

Pythoneditable
for value in ["Ana", "   ", ""]:
    blank = not value.strip()
    print(repr(value), "blank" if blank else "filled")
Output
'Ana' filled
'   ' blank
'' blank

not value.strip() treats an empty string and a string of spaces the same way.

4Count spaces and other whitespace

Pythoneditable
text = "one two\tthree\nfour"
print(sum(1 for c in text if c.isspace()))
Output
3

Common mistakes

Using isspace() to test for empty input

"".isspace() is False, so an empty answer slips through. Use not text.strip().

Pythoneditable
answer = ""
if answer.isspace():
    print("blank (isspace)")
if not answer.strip():
    print("blank (strip)")
Output
blank (strip)

Questions people ask

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

if not text.strip(): is True for both.

Is a non-breaking space whitespace?

Yes, "\u00a0".isspace() is True.

How do I remove all whitespace from a string?

"".join(text.split()) removes every space, tab and new line.

Spotted a mistake on this page? Tell us