Does Python have something like an empty string variable where you can do:
if myString == string.empty:
Regardless, what\'s the most elegan
If you want to differentiate between empty and null strings, I would suggest using if len(string)
, otherwise, I'd suggest using simply if string
as others have said. The caveat about strings full of whitespace still applies though, so don't forget to strip
.
I find this elegant as it makes sure it is a string and checks its length:
def empty(mystring):
assert isinstance(mystring, str)
if len(mystring) == 0:
return True
else:
return False
From PEP 8, in the “Programming Recommendations” section:
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
So you should use:
if not some_string:
or:
if some_string:
Just to clarify, sequences are evaluated to False
or True
in a Boolean context if they are empty or not. They are not equal to False
or True
.
not str(myString)
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.
I did some experimentation with strings like '', ' ', '\n', etc. I want isNotWhitespace to be True if and only if the variable foo is a string with at least one non-whitespace character. I'm using Python 3.6. Here's what I ended up with:
isWhitespace = str is type(foo) and not foo.strip()
isNotWhitespace = str is type(foo) and not not foo.strip()
Wrap this in a method definition if desired.
str = ""
if not str:
print "Empty String"
if(len(str)==0):
print "Empty String"