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

PythonServer Side ProgrammingProgramming

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!
raja
Published on 13-Dec-2017 14:24:20
Advertisements