Categories
comparison-operators python string

How to check if the string is empty?

1925

Does Python have something like an empty string variable where you can do:

if myString == string.empty:

Regardless, what’s the most elegant way to check for empty string values? I find hard coding "" every time for checking an empty string not as good.

2

  • 10

    How is "" not as good?

    – NoName

    Feb 8, 2020 at 23:19

  • None won’t match “”. So depends on the context as to what you want.

    Jul 9 at 17:05

2802

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.

16

  • 265

    Be careful, since lots of other things are false as well.

    Mar 5, 2012 at 20:11

  • 13

    I never heard of the term falsy before. Does it mean it returns false?

    Mar 5, 2012 at 20:15

  • 47

    @Joan: It evaluates as false in a boolean context.

    Mar 5, 2012 at 20:16

  • 76

    OP wants to know if the variable is an empty string, but you would also enter the if not myString: block if myString were None, 0, False etc. So if you aren’t sure what type myString is, you should use if myString == "": to determine if it is an empty string as opposed to some other falsy value.

    Aug 7, 2013 at 16:08

  • 36

    @AndrewClark, for such a case, instead of a chain of if myString == ... expressions, we could use if myString in (None, '') or per @Bartek, if myString in (None, '') or not myString.strip()

    – Stew

    Jun 12, 2015 at 19:43


502

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.

2

  • 4

    PS: In the PEP’s defense, one could argue that saying “x is false” (lowercase false) already means that, rather than meaning x == False. But IMHO the clarification is still welcome given the target audience.

    Mar 12, 2016 at 16:24


  • if not myString catch as empty this var='' in python 3.8

    – NikSp

    Jul 15 at 15:21


321

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.

0