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.

10
  • 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. Commented Oct 7, 2015 at 7:53
  • 1
    @jonrsharpe was trying to say it was wrong ended up writing that Commented Oct 7, 2015 at 7:57
  • 1
    @LinMa both does the same thing the myString == "" checks if string is empty explicitly not myString checks if string is empty implicitly Commented Oct 7, 2015 at 8: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 Commented Oct 7, 2015 at 8:17
  • 1
    @LinMa I believe they mean just if not '':, not actually referring to myString in that example Commented Oct 7, 2015 at 9:15

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.