0

What are the differences between the two methods?

if myString == ""

if not myString:

I read Most elegant way to check if the string is empty in Python? before asking, but it doesn't clarify their differences.

Community
  • 1
  • 1
Lin Ma
  • 9,739
  • 32
  • 105
  • 175
  • I read the post before asking, in that post, it is not clarified their differences. Please feel free to correct me if I am wrong. – Lin Ma Oct 07 '15 at 07:53
  • 1
    @jonrsharpe was trying to say it was wrong ended up writing that – The6thSense Oct 07 '15 at 07:57
  • @jonrsharpe, corrected my question. Your insights are appreciated. Thanks. – Lin Ma Oct 07 '15 at 08:11
  • @VigneshKalai, corrected my question. Your insights are appreciated. Thanks. – Lin Ma Oct 07 '15 at 08:11
  • 1
    @LinMa both does the same thing the `myString == ""` checks if string is empty explicitly `not myString` checks if string is empty implicitly – The6thSense Oct 07 '15 at 08:14
  • 1
    @LinMa by default `not ""` will be False like wise `not [],not 0,not {} etc..` but it is said to use `if myString == ""` because it is more readable – The6thSense Oct 07 '15 at 08:17
  • @VigneshKalai, nice catch, and if you could specify more what do you mean implicitly, it will be great. :) – Lin Ma Oct 07 '15 at 08:24
  • @VigneshKalai, thanks for the inputs. For your comments about method of not "", what is the complete statement -- if myString not ""? It seems syntax is not correct? – Lin Ma Oct 07 '15 at 08:26
  • 1
    @LinMa I believe they mean just `if not '':`, not actually referring to `myString` in that example – jonrsharpe Oct 07 '15 at 09:15
  • @jonrsharpe, I have two lines of code, which line do you mean? Thanks. – Lin Ma Oct 07 '15 at 19:11

1 Answers1

2

Both approaches will tell you, given a string object foo, whether it's an empty string or not:

>>> foo = ''
>>> foo == ''
True
>>> not foo
True
>>> foo = 'foo'
>>> foo == ''
False
>>> not foo
False

However, given an arbitrary object bar, you will get different results:

>>> bar = []  # empty list
>>> bar == ''
False  # isn't an empty string
>>> not bar
True  # but is still empty

Testing the truthiness works for many different kinds of object (see the docs), so not x will tell you whenever you have an "empty" object, but x == '' will only tell you whether or not you have an empty string. Which behaviour you need will depend on the situation you're in:

  • if it's definitely a string and you want to know if it's an empty string, you can use either (but not is neater);
  • if it's an arbitrary object and you want to know if it's an empty string, you need to use == ''; and
  • if it's an arbitrary object and you want to know if it's empty, you need to use not.
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437