Python str.isspace() function


In Python, the str.isspace() method is used to check if all characters in a string are whitespace characters. This method returns True if the string consists only of whitespace characters and contains at least one character; otherwise, it returns False.

Syntax

str.isspace()

Example Usage

  1. Basic usage with spaces:
text = " " result = text.isspace() print(result) # Output: True
  1. Including other whitespace characters:
text = "\t\n" # Tab and newline are also considered whitespace result = text.isspace() print(result) # Output: True
  1. Checking a string with mixed characters:
text = " Hello " result = text.isspace() print(result) # Output: False (contains non-whitespace characters)
  1. Empty string:
text = "" result = text.isspace() print(result) # Output: False (empty string has no characters)
  1. String with non-whitespace characters:
text = "Hello World" result = text.isspace() print(result) # Output: False (contains letters)

Important Notes

  • The isspace() method recognizes various whitespace characters, including:
    • Space (' ')
    • Tab ('\t')
    • Newline ('\n')
    • Carriage return ('\r')
    • Vertical tab ('\v')
    • Form feed ('\f')
  • It returns False for strings that contain any characters that are not whitespace.

Summary

  • Use str.isspace() to determine if a string consists entirely of whitespace characters.
  • It returns True for strings made up solely of whitespace (including tabs and newlines) and False for strings containing any non-whitespace characters.