user514310
user514310

Reputation:

Remove strings containing only white spaces from list

How do I delete empty strings from a list? I tried like this:

starring = ['Vashu Bhagnani', 'Khemchand Bhagnani', ' ', 'Jacky Bhagnani', ' ', 'Prashant Shah', ' ']
output = filter(bool, starring)

Output I want:

['Vashu Bhagnani', 'Khemchand Bhagnani',  'Jacky Bhagnani',  'Prashant Shah']

But output ends up being the same as input. What's the correct function to pass to filter?

Upvotes: 16

Views: 18594

Answers (3)

David Webb
David Webb

Reputation: 193686

Only the empty string evaluates to False so you need to use strip() to remove any whitespace and we can then rely on non-blank strings being evaluated as true.

>>> starring = ['Vashu Bhagnani', 'Khemchand Bhagnani', ' ', 'Jacky Bhagnani', ' ', 'Prashant Shah', ' ']                                      
>>> starring = filter(lambda name: name.strip(), starring)
>>> starring
['Vashu Bhagnani', 'Khemchand Bhagnani', 'Jacky Bhagnani', 'Prashant Shah']

Although a list comprehension might be easier:

>>> [name for name in starring if name.strip()]
['Vashu Bhagnani', 'Khemchand Bhagnani', 'Jacky Bhagnani', 'Prashant Shah']

Upvotes: 25

Felix Kling
Felix Kling

Reputation: 816364

You can remove trailing and leading white spaces, which will result in an empty string if it only contains those.

List comprehension:

l = [x for x in l if x.strip()]

With filter and operator.methodcaller [docs]:

l = filter(operator.methodcaller('strip'), l)

or simpler:

l = filter(str.strip, l)

operator.methodcaller would be the only way if you'd want to pass additional arguments to the method.

Upvotes: 9

ceth
ceth

Reputation: 45295

s = ['Vashu Bhagnani', 'Khemchand Bhagnani', '', 'Jacky Bhagnani', '', 'Prashant Shah', '']
[a for a in s if len(a) > 0]

Upvotes: 0

Related Questions