Remove empty strings from a list of strings

后端 未结 12 1500
孤城傲影
孤城傲影 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:11

    As reported by Aziz Alto filter(None, lstr) does not remove empty strings with a space ' ' but if you are sure lstr contains only string you can use filter(str.strip, lstr)

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

    Compare time on my pc

    >>> from timeit import timeit
    >>> timeit('" ".join(lstr).split()', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
    3.356455087661743
    >>> timeit('filter(str.strip, lstr)', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
    5.276503801345825
    

    The fastest solution to remove '' and empty strings with a space ' ' remains ' '.join(lstr).split().

    As reported in a comment the situation is different if your strings contain spaces.

    >>> lstr = ['hello', '', ' ', 'world', '    ', 'see you']
    >>> lstr
    ['hello', '', ' ', 'world', '    ', 'see you']
    >>> ' '.join(lstr).split()
    ['hello', 'world', 'see', 'you']
    >>> filter(str.strip, lstr)
    ['hello', 'world', 'see you']
    

    You can see that filter(str.strip, lstr) preserve strings with spaces on it but ' '.join(lstr).split() will split this strings.

提交回复
热议问题