str.isspace()
Returns True when a string is not empty and holds only whitespace: spaces, tabs, new lines and similar blank characters.
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
print(" ".isspace())
print("\t\n".isspace())
print(" a ".isspace())
print("".isspace())True True False False
2Skip blank lines in a file
with open("list.txt") as f:
for line in f:
if line.isspace():
continue
print(line.rstrip())apples pears plums
3Is a form field really filled in?
for value in ["Ana", " ", ""]:
blank = not value.strip()
print(repr(value), "blank" if blank else "filled")'Ana' filled ' ' blank '' blank
not value.strip() treats an empty string and a string of spaces the same way.
4Count spaces and other whitespace
text = "one two\tthree\nfour"
print(sum(1 for c in text if c.isspace()))3
Common mistakes
Using isspace() to test for empty input
"".isspace() is False, so an empty answer slips through. Use not text.strip().
answer = ""
if answer.isspace():
print("blank (isspace)")
if not answer.strip():
print("blank (strip)")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.