从列表中删除仅包含空格的字符串

时间:2011-12-09 17:35:27

标签: python

如何从列表中删除空字符串?我试过这样:

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

我想要的输出:

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

output最终与input相同。传递给filter的正确功能是什么?

3 个答案:

答案 0 :(得分:22)

只有空字符串的计算结果为False,因此您需要使用strip()删除任何空格,然后我们可以依赖非空字符串进行评估为真。

>>> 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']

虽然列表理解可能更容易:

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

答案 1 :(得分:7)

您可以删除尾随和前导空格,如果只包含空格,则会产生空字符串。

列表理解:

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

使用filteroperator.methodcaller [docs]

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

或更简单:

l = filter(str.strip, l)
如果您想要向该方法传递其他参数,

operator.methodcaller将是唯一的方法。

答案 2 :(得分:1)

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