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