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 providesisspace()
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:
- ' ' - Space
- '\t' - Horizontal tab
- '\n' - Newline
- '\v' - Vertical tab
- '\f' - Feed
- '\r' - Carriage return
isspace()
method.
yourString.isspace()
Example 1:
yesorno = " ".isspace()
print(yesorno);
Output:
True
Example 2:
yesorno = " nospace ".isspace()
print(yesorno);
Output:
FalseIf 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