+7 votes
in Python by (220 points)
edited by

Does Python have something like an empty string variable where you can do:

if myString == string.empty:

Regardless, what's the most elegant way to check for empty string values? I find hard coding "" every time for checking an empty string not as good. 

3 Answers

+9 votes
by (10.9k points)
edited by

In Boolean context, sequences are evaluated either as FALSE or TRUE and empty strings are considered as false. 

So you can simply check if the string is false using:

if not mystring:

You can also use the strip() method:

if myString.strip():

print("not an empty string")


print("empty string") 

In case, the variable is something other than a string, use this:

 myString== “ “

If you wish to know what is python visit this python tutorial and python interview questions.

by (19.8k points)
This worked for me!
by (39.2k points)
A simple solution could be like this:
def isStringEmpty(inputString):
    if len(inputString) == 0:
        return True
        return False
by (47.2k points)
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!"
by (44.6k points)
But notice that, if your string is an empty space, the .strip() method will provide FALSE.
by (31.8k points)
This should work for you @chandini.
It certainly worked for me.
+4 votes
by (107k points)
edited by

To check if the string is empty you should use the following methods:  

if not some_string:

Or you have another that you can use:

if some_string:

One point you should note that the sequences(string, tuples etc) are evaluated to False or True in a Boolean context if they are empty or not. They are not equal to False or True.

You can use the following video tutorials to clear all your doubts:-

by (29.9k points)
This helps me a lot thank you.
by (19.2k points)
Nice Explanation, Thank You.
+2 votes
by (29.8k points)

I think the most elegant way is using the following

if not myString:

simply for the fact that Empty strings are " considered false in a Boolean context, so you can just use the above

by (25.3k points)
However, you may want to strip white space because:

 >>> bool("")
 >>> bool("   ")
 >>> bool("   ".strip())

You have to be explicit in this unless you know for sure that this string has passed some sort of validation and is a string that can be tested this way.
by (105k points)
Very well explained!
by (33.2k points)
It worked for me.

Related questions

+3 votes
2 answers
+3 votes
2 answers
0 votes
2 answers
asked May 30, 2019 in Python by Anvi (10.2k points)
+3 votes
2 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers !