Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty entries during string split

Currently I use this helper function to remove the empty entries.

Is there a built-in way for this?

def getNonEmptyList(str, splitSym):
    lst=str.split(splitSym)

    lst1=[]
    for entry in lst:
        if entry.strip() !='':
            lst1.append(entry)

    return lst1
like image 992
william007 Avatar asked Oct 23 '17 04:10

william007


Video Answer


3 Answers

str.split(sep=None, maxsplit=-1)

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

For example:

>>> '1 2 3'.split()
['1', '2', '3']
>>> '1 2 3'.split(maxsplit=1)
['1', '2 3']
>>> '   1   2   3   '.split()
['1', '2', '3']
like image 164
srikavineehari Avatar answered Nov 05 '22 04:11

srikavineehari


This split could be done more compactly with a comprehension like:

def getNonEmptyList(str, splitSym):
    return [s for s in str.split(splitSym) if s.strip() != '']
like image 42
Stephen Rauch Avatar answered Nov 05 '22 03:11

Stephen Rauch


You could use filter

def get_non_empty_list(s, delimiter):
    return list(filter(str.strip, s.split(delimiter)))
like image 38
Jack Homan Avatar answered Nov 05 '22 05:11

Jack Homan