views:

612

answers:

3

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.

+13  A: 
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.

Vladislav
what's the point of `replace` here? this second method will create new string, btw
SilentGhost
You are correct. strip() should remove the new line. Fixed it.
Vladislav
Thanks! (15 char limit)
bodacydo
+5  A: 

isspace

SilentGhost
why the downvote?
SilentGhost
I didn't downvote. I upvoted. :) (Maybe someone else downvoted because of shortness of the answer.)
bodacydo
+1  A: 
>>> tests = ['foo', ' ', '\r\n\t', '', None]
>>> [bool(not s or s.isspace()) for s in tests]
[False, True, True, True, True]
>>>
John Machin