如何删除列表中的空字符串? [英] How to remove empty string in a list?

查看:150
本文介绍了如何删除列表中的空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有一个句子

"He is so .... cool!"

然后,我删除所有标点符号并将其放在列表中.

Then I remove all the punctuation and make it in a list.

["He", "is", "so", "", "cool"]

如何删除或忽略空字符串?

How do I remove or ignore the empty string?

推荐答案

您可以使用 filter ,其中以None作为键函数,该过滤器过滤掉所有False ish元素(包括空字符串)

You can use filter, with None as the key function, which filters out all elements which are Falseish (including empty strings)

>>> lst = ["He", "is", "so", "", "cool"]
>>> filter(None, lst)
['He', 'is', 'so', 'cool']

但是请注意,filter在Python 2中返回一个列表,但是在Python 3中返回一个生成器.您将需要在Python 3中将其转换为列表,或者使用列表理解解决方案.

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值包括:

False
None
0
''
[]
()
# and all other empty containers

这篇关于如何删除列表中的空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆