Python String isspace() Method – Check for Whitespace Only

Python String isspace() Method

The isspace() method in Python checks whether all characters in a string are whitespace characters like space, tab, newline, etc. It returns True if the string contains only whitespace and is not empty.

Syntax

string.isspace()

Returns:

  • True – if the string has only whitespace characters
  • False – if the string contains any non-whitespace character or is empty

Example 1: Basic Usage

text = "   "
print(text.isspace())
True

Since the string contains only spaces, isspace() returns True.

Example 2: Including Tabs and Newlines

text = "\t\n "
print(text.isspace())
True

Tabs (\t) and newlines (\n) are also considered whitespace characters.

Example 3: String with Non-Whitespace

text = " abc "
print(text.isspace())
False

Even one non-whitespace character makes the method return False.

Example 4: Empty String

text = ""
print(text.isspace())
False

isspace() does not return True for empty strings.

Use Cases

  • To validate input that should be empty or whitespace only
  • To filter out blank lines when processing files
  • To check for formatting issues in text

Common Mistakes

  • Assuming "" (empty string) returns True – it returns False
  • Using it on non-string objects – you must call it on a string

Interview Tip

In text cleaning or validation tasks, isspace() is useful for quickly checking if a line or user input is just whitespace.

Summary

  • string.isspace() checks if a string contains only whitespace characters
  • Returns False for empty strings or if any character is non-whitespace
  • Whitespace includes spaces, tabs, newlines, etc.

Practice Problem

Write a program that asks the user to enter something and checks if they entered only spaces:

user_input = input("Enter something: ")
if user_input.isspace():
    print("Only whitespace entered.")
else:
    print("Contains non-whitespace characters.")