关于Python从列表中删除仅含空格的字符串

Remove strings containing only white spaces from list

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

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

我想要的输出:

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

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


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

1
2
3
4
>>> 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']

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

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


可以删除尾随空格和前导空格,如果只包含这些空格,则会导致空字符串。

列表理解:

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

使用filteroperator.methodcaller文件:

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

或更简单:

1
l = filter(str.strip, l)

如果您想向该方法传递其他参数,那么只有operator.methodcaller是唯一的方法。


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