Check a String Is Empty in a Pythonic Way

You have different methods to check whether a string is an empty string in Python. Like,

>>> A = ""
>>> A == ""
>>> A is ""
>>> not A

The last method not A is a Pythonic way recommended by Programming Recommendations in PEP8. By default, empty sequences and collections are evaluated as False in a Boolean context.

not A is recommended not only because it is Pythonic, but also because it is the most efficient.

>>> timeit.timeit('A == ""', setup='A=""',number=10000000)
>>> timeit.timeit('A is ""', setup='A=""',number=10000000)
>>> timeit.timeit('not A', setup='A=""',number=10000000)
Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python String

  • Remove Commas From String in Python
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python