Computer >> Computer tutorials >  >> Programming >> Python

What is the most elegant way to check if the string is empty in Python?


Empty strings are "falsy" which means they are considered false in a Boolean context, so you can just use not string.  

example

string = ""
if not string:
    print "Empty String!"

Output

This will give the output:

Empty String!

Example

If your string can have whitespace and you still want it to evaluate to false, you can just strip it and check again. For example:

string = "   "
if not string.strip():
    print "Empty String!"

Output

This will give the output:

Empty String!