The Python Oracle

How to check if the string is empty?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Thinking It Over

--

Chapters
00:00 Question
00:26 Accepted answer (Score 2901)
01:00 Answer 2 (Score 517)
01:41 Answer 3 (Score 326)
02:20 Answer 4 (Score 117)
02:56 Thank you

--

Full question
https://stackoverflow.com/questions/9573...

Accepted answer links:
[python 2]: http://docs.python.org/2/library/stdtype...
[python 3]: https://docs.python.org/3/library/stdtyp...
[Truth Value Testing]: http://docs.python.org/library/stdtypes....

Answer 2 links:
[PEP 8]: http://www.python.org/dev/peps/pep-0008/
[“Programming Recommendations” section]: https://www.python.org/dev/peps/pep-0008...

Answer 4 links:
[Apache's StringUtils.isBlank]: https://commons.apache.org/proper/common...-
[Guava's Strings.isNullOrEmpty]: https://google.github.io/guava/releases/...)

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #comparisonoperators

#avk47



ACCEPTED ANSWER

Score 3080


Empty strings are "falsy" (python 2 or python 3 reference), which means they are considered false in a Boolean context, so you can just do this:

if not myString:

This is the preferred way if you know that your variable is a string. If your variable could also be some other type then you should use:

if myString == "":

See the documentation on Truth Value Testing for other values that are false in Boolean contexts.




ANSWER 2

Score 548


From PEP 8, in the “Programming Recommendations” section:

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

So you should use:

if not some_string:

or:

if some_string:

Just to clarify, sequences are evaluated to False or True in a Boolean context if they are empty or not. They are not equal to False or True.




ANSWER 3

Score 347


The most elegant way would probably be to simply check if its true or falsy, e.g.:

if not my_string:

However, you may want to strip white space because:

 >>> bool("")
 False
 >>> bool("   ")
 True
 >>> bool("   ".strip())
 False

You should probably be a bit more explicit in this however, unless you know for sure that this string has passed some kind of validation and is a string that can be tested this way.




ANSWER 4

Score 135


I would test noneness before stripping. Also, I would use the fact that empty strings are False (or Falsy). This approach is similar to Apache's StringUtils.isBlank or Guava's Strings.isNullOrEmpty

This is what I would use to test if a string is either None OR empty OR blank:

def isBlank (myString):
    return not (myString and myString.strip())

And the exact opposite to test if a string is not None NOR empty NOR blank:

def isNotBlank (myString):
    return bool(myString and myString.strip())