Not vs "" when checking for empty strings

What’s the difference between using the not keyword and the empty quotes ("") for a string?

for example:

string = ""

if not string:


if string == "":

The not keyword is a logical operator.

What your code actually does is performing two different operations leading to the same result :slight_smile:

Case 1:

>>> bool('')
>>> not False

See? You assign variable string value '' which in boolean (logic) format has value False. Because it is empty. For instance, bool('something') returns True.

So your first comparison effectively says: if NOT FALSE then … And you get your print statement executed. Because NOT FALSE is TRUE :slight_smile:

Case 2:

You just compare '' == '' because your variable string has value ''. And this gives us TRUE again, but because two objects are equal.


In other words, you are doing the following:

Case 1: if [not false] then do…
Case 2: if [value of object 1 is the same as value of object 2] then do…

In first case you have logical condition, while in second you compare values themselves.

Hope this adds some meaning :slight_smile:

In this example, both cases will give the same results.
When we step back and think about these operators, the process to the same result are completely different.
In 2nd case, it is a very restrictive condition. Empty is only printed if string is that empty string. It will not print if any other value is given (no matter string or not).
In 1st case, the condition is less restrictive. Anything that string represents that evaluates to False will become True after not operation and Empty will be printed. To evaluate to false, the empty string in case 1 is one example, but many other things can evaluate to False too, such as dict(), set(), list(), {}. When testing the code, you then have to watch out that the string variable is really a string type as you expect, then check that it is an empty string.

Basically, it is easier to pass the 1st if condition. Easier meaning string can take on more values. That could be good or bad depending on what you expect the user to input, or what values could flow down to this part of the code from upstream code. This kind of thing is similar to Exception Handling where you decide which exceptions to catch, or logging when you decide what level to log at.

It’s clear for me now, thanks!