Suppose I have a empty string, it will be split:
>>>''.split(',')
['']
The result of the split is ['']
. I use bool
to check it whether or not it's empty. It will return True
.
>>>bool([''])
True
How do I check the split result is empty?
listpythonpython-2.7
Suppose I have a empty string, it will be split:
>>>''.split(',')
['']
The result of the split is ['']
. I use bool
to check it whether or not it's empty. It will return True
.
>>>bool([''])
True
How do I check the split result is empty?
Best Answer
With
bool([''])
you're checking if the list['']
has any contents, which it does, the contents just happen to be the empty string''
.If you want to check whether all the elements in the list aren't 'empty' (so if the list contains the string
''
it will returnFalse
) you can use the built-in functionall()
:This takes every element
v
in listl
and checks if it has aTrue
value; if all elements do it returnsTrue
if at least one doesn't it returnsFalse
. As an example:You can substitute this with
any()
to perform a partial check and see if any of the items in the listl
have a value ofTrue
.A more comprehensive example* with both uses:
*As @ShadowRanger pointed out in the comments, the same exact thing can be done with
all(l)
orany(l)
since they both just accept an iterable in the end.