Check if string contains only whitespace

bodacydo picture bodacydo · Mar 8, 2010 · Viewed 234.9k times · Source

How can I test if a string contains only whitespace?

Example strings:

  • " " (space, space, space)

  • " \t \n " (space, tab, space, newline, space)

  • "\n\n\n\t\n" (newline, newline, newline, tab, newline)

Answer

Vladislav picture Vladislav · Mar 8, 2010

Use the str.isspace() method:

Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.

A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S.

Combine that with a special case for handling the empty string.

Alternatively, you could use str.strip() and check if the result is empty.