How to check if text is "empty" (spaces, tabs, newlines) in Python?


Question

How can I test if the string is empty in Python?

For example,

"<space><space><space>" is empty, so is

"<space><tab><space><newline><space>", so is

"<newline><newline><newline><tab><newline>", etc.

1
183
3/8/2010 10:29:25 PM

Accepted Answer

yourString.isspace()

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

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

Alternatively, you could use

strippedString = yourString.strip()

And then check if strippedString is empty.

271
3/8/2010 10:54:35 PM

>>> tests = ['foo', ' ', '\r\n\t', '', None]
>>> [bool(not s or s.isspace()) for s in tests]
[False, True, True, True, True]
>>>

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon