Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท String Methods

Python str.isspace() method

Reference for Python str.isspace(): test whether a string contains only whitespace, why empty strings are False, and how to detect blank lines and input.

The isspace() method returns True if the string is not empty and every character is whitespace: spaces, tabs, newlines and carriage returns, plus other Unicode space characters such as the non-breaking space.

Its most common job is spotting blank lines or fields that contain nothing but spaces.

Python
print("  \t\n".isspace())   # True
print(" a ".isspace())      # False

Try it

Python What counts as whitespace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Skipping blank lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
str.isspace()

This method takes no parameters.

Return value: True if the string has at least one character and all characters are whitespace; otherwise False.

Raises: nothing.

Usage notes

  • Empty is False. "".isspace() is False. To test "empty or only spaces" in one step, use not text.strip().
  • Unicode whitespace. A character counts if its bidirectional type is WS, B or S, or its category is Zs. That covers the non-breaking space (ย ) and the em space (โ€ƒ).
  • Zero-width space is not whitespace. "โ€‹".isspace() is False, so such text survives strip() and isspace() alike. See isprintable() for finding it.
  • Same set as split() and strip(). Calling split() with no argument or strip() with no argument removes the characters isspace() accepts.
  • Form validation. A required field containing only spaces is truthy (bool(" ") is True), so test not value.strip() before accepting it.
  • Bytes have bytes.isspace() that accepts only ASCII whitespace.