HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

How to check if the string is empty in Python?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
emptyhowcheckthestringpython

Problem

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.

Solution

Empty strings are "falsy" (python 2 or python 3 reference), which means they are considered false in a Boolean context, so you can just do this:

if not myString:


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:

if myString == "":


See the documentation on Truth Value Testing for other values that are false in Boolean contexts.

Code Snippets

if not myString:
if myString == "":

Context

Stack Overflow Q#9573244, score: 3161

Revisions (0)

No revisions yet.