bytes.isspace() returns True if the object is not empty and every byte is one of the six ASCII whitespace bytes: space, \t, \n, \r, \x0b (vertical tab), and \x0c (form feed).
These are the same bytes that strip() and split() treat as whitespace by default. Bytes like \x00, \x1c, and \xa0 are not whitespace for bytes.
bytes.isspace() is a method of the built-in bytes type: call it on a bytes object with dot notation, such as data.isspace(...). No import is needed, and bytearray objects have the same method.
Syntax
No arguments; returns a bool.
python
result = data.isspace()
Call
What it does
b" \t\n".isspace()
Returns True.
b" x ".isspace()
Returns False.
b"".isspace()
Returns False.
A common blank-line test is not line.strip(), which is also True for empty lines.
Method signatures
python
bytes.isspace()
# returns True or False; bytearray.isspace() works the same way
Parameters
isspace() takes no parameters.
Return Value
Return Value
Description
True
At least one byte, and all are ASCII whitespace.
False
Empty, or contains any other byte.
Python Examples
Example 1 — Skip Whitespace-Only Lines
Split data into lines, then keep only lines with real content. Empty lines are filtered by the truth test, whitespace-only lines by isspace().
python
data = b"a\n \t\n\r\nb\n"
lines = data.split(b"\n")
print(lines)
print([line for line in lines if line and not line.isspace()])
Output
[b'a', b' \t', b'\r', b'b', b'']
[b'a', b'b']
How It Works
Raw lines. Splitting on LF leaves a space-tab line, a lone CR, and an empty last item.
Two filters.line removes the empty item, and not line.isspace() removes lines made of whitespace.
CR is whitespace. The leftover \r from a CRLF ending is dropped too.
Example 2 — Exactly Which Bytes Are Whitespace
Test all six whitespace bytes together, then three bytes that look like whitespace but are not.
python
for chunk in [b" \t\n\r\x0b\x0c", b"\x00", b"\xa0", b"\x1c", b""]:
print(chunk, chunk.isspace())