How to check if a string is empty (whitespaces, newlines or tabs) in python?

How to check if a string is empty i.e contains only whitespaces, newlines, or tabs in python?

Python provides isspace() method which returns true if there are only whitespaces in a string and there is at least one character in given string. It returns false otherwise.

A whitespace can be any of the following:
  1. ' ' - Space
  2. '\t' - Horizontal tab
  3. '\n' - Newline
  4. '\v' - Vertical tab
  5. '\f' - Feed
  6. '\r' - Carriage return
Syntax to use isspace() method.
yourString.isspace()

Example 1:

yesorno = "     ".isspace()

print(yesorno);

Output:

True

Example 2:

yesorno = "   nospace  ".isspace()

print(yesorno);

Output:

False
If you just want to check if a string is empty or not there is an alternative way, you can simply use strip() method to check if a string is empty.

Example 3:

tokens = "     ".strip()

print(tokens=="");

Output:

True

Comments