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.
print(" \t\n".isspace()) # True print(" a ".isspace()) # False
Try it
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.
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
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()isFalse. To test "empty or only spaces" in one step, usenot text.strip(). - Unicode whitespace. A character counts if its bidirectional type is
WS,BorS, or its category isZs. That covers the non-breaking space (ย) and the em space (โ). - Zero-width space is not whitespace.
"โ".isspace()isFalse, so such text survivesstrip()andisspace()alike. Seeisprintable()for finding it. - Same set as
split()andstrip(). Callingsplit()with no argument orstrip()with no argument removes the charactersisspace()accepts. - Form validation. A required field containing only spaces is truthy (
bool(" ")isTrue), so testnot value.strip()before accepting it. - Bytes have
bytes.isspace()that accepts only ASCII whitespace.