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.
In my experience testing for
""
doesn't always work. This simple tests has always worked for me:or
Reading an Excel spreadsheet I want to stop when a column gets empty using the following while loop:
As prmatta posted above, but with mistake.
From PEP 8, in the “Programming Recommendations” section:
So you should use:
or:
Just to clarify, sequences are evaluated to
False
orTrue
in a Boolean context if they are empty or not. They are not equal toFalse
orTrue
.The most elegant way would probably be to simply check if its true or falsy, e.g.:
However, you may want to strip white space because:
You should probably be a bit more explicit in this however, unless you know for sure that this string has passed some kind of validation and is a string that can be tested this way.
This expression is True for strings that are empty. Non-empty strings, None and non-string objects will all produce False, with the caveat that objects may override __str__ to thwart this logic by returning a falsy value.