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'] |
但是,
只有空字符串的计算结果为
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()] |
使用
1 | l = filter(operator.methodcaller('strip'), l) |
或更简单:
1 | l = filter(str.strip, l) |
如果您想向该方法传递其他参数,那么只有
1 2 | s = ['Vashu Bhagnani', 'Khemchand Bhagnani', '', 'Jacky Bhagnani', '', 'Prashant Shah', ''] [a for a in s if len(a) > 0] |