10

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
2
  • If your data didn't have extra whitespace, you wouldn't have to do this Commented Oct 23, 2017 at 4:28
  • 3
    You can use: lst1 = [x for x in str.split(splitSym) if x] Commented Oct 23, 2017 at 4:30

5 Answers 5

10

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']
Sign up to request clarification or add additional context in comments.

Comments

4

You could use filter

def get_non_empty_list(s, delimiter):
    return list(filter(str.strip, s.split(delimiter)))

Comments

3

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() != '']

Comments

3

If you want to split text by newline and remove any empty lines here's one liner :)

lines = [l for l in text.split('\n') if l.strip()]

Comments

0

You can use a regex to capture the extra whitespace.

import re 
split_re = r'\s*{}\s*'.format(splitSym)
return re.split(split_re, string) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.