Python String isspace() Function
The String isspace()
method returns True
if the string is not empty and all characters are whitespace characters. Otherwise, it returns False
.
Syntax
my_string.isspace()
isspace() Parameters
Python String isspace()
function does not take any parameters.
isspace() Return Value
Python String isspace()
function returns:
True
if all characters in the string are whitespace characters.False
if the string contains at least one non-whitespace character or if the string is empty.
Examples
Example 1: Check if a String contains all whitespaces with isspace()
The isspace()
method returns True
if all characters in the string are whitespace characters.
my_str = ' '
print(my_str.isspace()) # Output: True
output
True
The isspace()
method returns False
if the string contains at least one non-whitespace character.
my_str = ' a'
print(my_str.isspace()) # Output: False
output
False
Example 2: Check if an Empty String contains whitespace with isspace()
The isspace()
method returns False
if string is empty.
my_str = ''
print(my_str.isspace()) # Output: False
output
False
What characters are Whitespaces?
The most common whitespace characters are space
, tab \t
, and newline \n
, but also Carriage Return \r
and ASCII Form Feed \f
are considered as whitespace characters.
Moreover, some Unicode characters qualify as whitespace:
Unicode Character | Description |
---|---|
U+0020 | Space |
U+00A0 | No-Break Space |
U+1680 | Ogham Space Mark |
U+2000 | En Quad |
U+2001 | Em Quad |
U+2002 | En Space |
U+2003 | Em Space |
U+2004 | Three-Per-Em Space |
U+2005 | Four-Per-Em Space |
U+2006 | Six-Per-Em Space |
U+2007 | Figure Space |
U+2008 | Punctuation Space |
U+2009 | Thin Space |
U+200A | Hair Space |
U+202F | Narrow No-Break Space |
U+205F | Medium Mathematical Space |
U+3000 | Ideographic Space |
Some examples:
my_str1 = ' \t \n \r \f '
my_str2 = '\u2005 \u2007'
print(my_str1.isspace()) # Output: True
print(my_str2.isspace()) # Output: True
output
True
True