Find if a string is empty in python

This blog post discusses which is the best method to find if a string is empty in python. We all would have known about the naive method. But let us see which one is the most effective and efficient method to find the empty string.

In the naive method we would do something just like this. This is for beginners and not recommended.

my_string = ''
if my_string == '':
    print('empty string')

Now let us look at the suggested method. Empty strings are “falsy” which means they are considered false in a Boolean context, so you can just do this:

my_string = ''
if not my_string:
    print('empty string')

This is the preferred way if you know that your variable is a string. If your variable could also be some other type then you should use

my_string == ''

The “Programming Recommendations” section from PEP 8 states that

"For sequences, (strings, lists, tuples), use the fact that empty sequences are false."


Hope this article is helpful. If you have any queries leave them in the comments below.

Happy coding!