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

546    Asked by JacobRutherford in Python , Asked on Mar 9, 2021

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. 

Answered by Jacob Rutherford

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


To solve the error “python string is empty” 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")

else:

print("empty string")

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

 myString== “ “



Your Answer

Interviews

Parent Categories