Remove empty strings from a list of strings

后端 未结 12 1738
孤城傲影
孤城傲影 2020-11-22 04:33

I want to remove all empty strings from a list of strings in python.

My idea looks like this:

while \'\' in str_list:
    str_list.remove(\'\')
         


        
12条回答
  •  星月不相逢
    2020-11-22 05:02

    >>> lstr = ['hello', '', ' ', 'world', ' ']
    >>> lstr
    ['hello', '', ' ', 'world', ' ']
    
    >>> ' '.join(lstr).split()
    ['hello', 'world']
    
    >>> filter(None, lstr)
    ['hello', ' ', 'world', ' ']
    

    Compare time

    >>> from timeit import timeit
    >>> timeit('" ".join(lstr).split()', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
    4.226747989654541
    >>> timeit('filter(None, lstr)', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
    3.0278358459472656
    

    Notice that filter(None, lstr) does not remove empty strings with a space ' ', it only prunes away '' while ' '.join(lstr).split() removes both.

    To use filter() with white space strings removed, it takes a lot more time:

    >>> timeit('filter(None, [l.replace(" ", "") for l in lstr])', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
    18.101892948150635
    

提交回复
热议问题