How do I check if the list contains empty elements?

时间:2016-02-03 03:02:24

标签: python list python-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?

5 个答案:

答案 0 :(得分:10)

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 return False) you can use the built-in function all():

all(v for v in l)

This takes every element v in list l and checks if it has a True value; if all elements do it returns True if at least one doesn't it returns False. As an example:

l = ''.split(',')

all(v for v in l)
Out[75]: False

You can substitute this with any() to perform a partial check and see if any of the items in the list l have a value of True.

A more comprehensive example* with both uses:

l = [1, 2, 3, '']

all(l)
# '' doesn't have a True value
Out[82]: False

# 1, 2, 3 have a True value
any(l)
Out[83]: True

*As @ShadowRanger pointed out in the comments, the same exact thing can be done with all(l) or any(l) since they both just accept an iterable in the end.

答案 1 :(得分:2)

If emptiness is the important result, probably best to test the original string first:

x = ''
if x:
    # Original string was non-empty, split it
    splitx = x.split(',')
    if any(splitx):
        # There was at least one character in the original string that wasn't a comma

The first test rules out empty initial strings, the second one using any rules out strings that were nothing but the split character, and therefore returned a whole bunch of empty strings, but no non-empty strings. As long as you got one non-empty string, it passes.

Note: In case you're trying to parse CSV files, don't use .split(','); there is a csv module that handles this correctly (including escapes, quoting, etc.), and should ALWAYS be used for parsing CSV, never roll your own parser. Added bonus: csv will convert '' inputs to [] rows, which you can test for truthiness directly, not to [''] like str.split does. Example:

>>> import csv, io

>>> f = io.StringIO('\n\na,b,c\n1,2,3\n\n')
>>> [row for row in csv.reader(f) if row]  # Stripping easily
[['a', 'b', 'c'], ['1', '2', '3']]

vs. the same approach with str.split(',') which still doesn't handle quoting, escaping, etc.:

>>> f = io.StringIO('\n\na,b,c\n1,2,3\n\n')
>>> stripped = (line.rstrip('\r\n') for line in f)  # Must manually strip line endings first
>>> [line.split(',') for line in stripped if line]
[['a', 'b', 'c'], ['1', '2', '3']]

答案 2 :(得分:1)

In your case it truly isnt empty

If you want to check if the element within that list is empty you can do:

string = ''.split(',')

if not string[0]:
    print "empty"

答案 3 :(得分:0)

The split result isn't empty. The sense of "emptiness" you're looking for is best checked by looking at the original, unsplit string:

if not original_string:
    # It's empty.

But if you really want to look at the split result for this:

if len(split_result) == 1 and not split_result[0]:
    # It's "empty".

答案 4 :(得分:0)

According to the str.split() documentation, "Splitting an empty string with a specified separator returns ['']."

To check for this case, when you are using an explicit delimiter (like your use of split(",")), do something like this:

l = s.split(",")

if len(l) == 1 and l[0] == '':
    print("string was empty")