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.
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.
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:
not
is neater);== ''
; and not
.