在字符串spli期间删除空项

2024-10-01 17:28:04 发布

您现在位置:Python中文网/ 问答频道 /正文

目前我使用这个helper函数来删除空条目。在

有没有内置的方法?在

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

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

    return lst1

Tags: 方法函数inhelperfordef条目内置
3条回答

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

^{bq}$

例如:

>>> '1 2 3'.split()
['1', '2', '3']
>>> '1 2 3'.split(maxsplit=1)
['1', '2 3']
>>> '   1   2   3   '.split()
['1', '2', '3']

你可以用过滤器

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

这种划分可以更紧凑地进行,理解如下:

def getNonEmptyList(str, splitSym):
    return [s for s in str.split(splitSym) if s.strip() != '']

相关问题 更多 >

    热门问题