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.
Responding to @1290. Sorry, no way to format blocks in comments. The
None
value is not an empty string in Python, and neither is (spaces). The answer from Andrew Clark is the correct one:if not myString
. The answer from @rouble is application-specific and does not answer the OP's question. You will get in trouble if you adopt a peculiar definition of what is a "blank" string. In particular, the standard behavior is thatstr(None)
produces'None'
, a non-blank string.However if you must treat
None
and (spaces) as "blank" strings, here is a better way:Examples:
Meets the @rouble requirements while not breaking the expected
bool
behavior of strings.for those who expect a behaviour like the apache StringUtils.isBlank or Guava Strings.isNullOrEmpty :
If you want to differentiate between empty and null strings, I would suggest using
if len(string)
, otherwise, I'd suggest using simplyif string
as others have said. The caveat about strings full of whitespace still applies though, so don't forget tostrip
.I haven't noticed THAT particular combination in any of the answers. I searched for
in the answers prior to posting.
I think this is what the original poster was trying to get to... something that reads as close to English as possible and follows solid programming practices.
Character for character I think this solution is a good one.
I noted
None
has entered into the discussion, so adding that and compacting further we get:Test empty or blank string (shorter way):
if stringname:
gives afalse
when the string is empty. I guess it can't be simpler than this.