Remove empty strings from a list of strings

2018-12-31 21:25发布

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('')

Is there any more pythonic way to do this?

14条回答
君临天下
2楼-- · 2018-12-31 21:45

List comprehensions

strings = ["first", "", "second"]
[x for x in strings if x]

Output: ['first', 'second']

Edit: Shortened as suggested

查看更多
不再属于我。
3楼-- · 2018-12-31 21:45

Depending on the size of your list, it may be most efficient if you use list.remove() rather than create a new list:

l = ["1", "", "3", ""]

while True:
  try:
    l.remove("")
  except ValueError:
    break

This has the advantage of not creating a new list, but the disadvantage of having to search from the beginning each time, although unlike using while '' in l as proposed above, it only requires searching once per occurrence of '' (there is certainly a way to keep the best of both methods, but it is more complicated).

查看更多
君临天下
4楼-- · 2018-12-31 21:45

filter(None, str) does not remove empty strings with a space ' ', it only prunes away '' and ' '.

join(str).split() removes both. but if your element of list having space then it will change your list elements also because it's joining first your all elements of list then spiting them by space so You should use : -

str = ['hello', '', ' ', 'world', ' ']
print filter(lambda x:x != '', filter(lambda x:x != ' ', str))

It will remove both and won't effect your elements also Like :-

str = ['hello', '', ' ', 'world ram', ' ']
print  ' '.join(lstr).split()
print filter(lambda x:x != '', filter(lambda x:x != ' ', lstr))

output:-

['hello', 'world', 'ram'] <-------------- output of ' '.join(lstr).split()
['hello', 'world ram']

查看更多
谁念西风独自凉
5楼-- · 2018-12-31 21:49
str_list = ['2', '', '2', '', '2', '', '2', '', '2', '']

for item in str_list:
    if len(item) < 1:  
        str_list.remove(item)

Short and sweet.

查看更多
不流泪的眼
6楼-- · 2018-12-31 21:51

Reply from @Ib33X is awesome. If you want to remove every empty string, after stripped. you need to use the strip method too. Otherwise, it will return the empty string too if it has white spaces. Like, " " will be valid too for that answer. So, can be achieved by.

strings = ["first", "", "second ", " "]
[x.strip() for x in strings if x.strip()]

The answer for this will be ["first", "second"].
If you want to use filter method instead, you can do like
list(filter(lambda item: item.strip(), strings)). This is give the same result.

查看更多
梦寄多情
7楼-- · 2018-12-31 21:56

To eliminate empties after stripping:

slist = map(lambda s: s and s.strip(), slist)
slist = filter(None, slist)

Some PROs:

  • lazy, based on generators, to save memory;
  • decent understandability of the code;
  • fast, selectively using builtins and comprehensions.

    def f1(slist):
        slist = [s and s.strip() for s in slist]
        return list(filter(None, slist))
    
    def f2(slist):
        slist = [s and s.strip() for s in slist]
        return [s for s in slist if s]
    
    
    def f3(slist):
        slist = map(lambda s: s and s.strip(), slist)
        return list(filter(None, slist))
    
    def f4(slist):
        slist = map(lambda s: s and s.strip(), slist)
        return [s for s in slist if s]
    
    %timeit f1(words)
    10000 loops, best of 3: 106 µs per loop
    
    %timeit f2(words)
    10000 loops, best of 3: 126 µs per loop
    
    %timeit f3(words)
    10000 loops, best of 3: 165 µs per loop
    
    %timeit f4(words)
    10000 loops, best of 3: 169 µs per loop
    
查看更多
登录 后发表回答