Python - How To Check a String Is Empty in a Pythonic Way

ID : 11

viewed : 255

Tags : PythonPython String

vote vote

90

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

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

The last method not A is a Pythonic way recommended by 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) 0.4620500060611903 >>> timeit.timeit('A is ""', setup='A=""',number=10000000) 0.36170379760869764 >>> timeit.timeit('not A', setup='A=""',number=10000000) 0.3231199442780053 

  • Related HOW TO?