python – Check if string contains only whitespace

python – Check if string contains only whitespace

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.

str.isspace() returns False for a valid and empty string

>>> tests = [foo,  , rnt, ]
>>> print([s.isspace() for s in tests])
[False, True, True, False]

Therefore, checking with not will also evaluate None Type and or (empty string)

>>> tests = [foo,  , rnt, , None, ]
>>> print ([not s or s.isspace() for s in tests])
[False, True, True, True, True, True]

python – Check if string contains only whitespace

You want to use the isspace() method

str.isspace()

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

Thats defined on every string object. Here it is an usage example for your specific use case:

if aStr and (not aStr.isspace()):
    print aStr

Leave a Reply

Your email address will not be published. Required fields are marked *