How to remove empty string in a list?
You can filter it like this
orig = ["He", "is", "so", "", "cool"]
result = [x for x in orig if x]
Or you can use filter
. In python 3 filter
returns a generator, thus list()
turns it into a list. This works also in python 2.7
result = list(filter(None, orig))
You can use filter
, with None
as the key function, which filters out all elements which are False
ish (including empty strings)
>>> lst = ["He", "is", "so", "", "cool"]
>>> filter(None, lst)
['He', 'is', 'so', 'cool']
Note however, that filter
returns a list in Python 2, but a generator in Python 3. You will need to convert it into a list in Python 3, or use the list comprehension solution.
False
ish values include:
False
None
0
''
[]
()
# and all other empty containers
You can use a list comprehension:
cleaned = [x for x in your_list if x]
Although I would use regex to extract the words:
>>> import re
>>> sentence = 'This is some cool sentence with, spaces'
>>> re.findall(r'(\w+)', sentence)
['This', 'is', 'some', 'cool', 'sentence', 'with', 'spaces']