如何删除列表中的空字符串?

2024-05-13 12:51:36 发布

您现在位置:Python中文网/ 问答频道 /正文

例如我有一句话

"He is so .... cool!"

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

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

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


Tags: 字符串列表soishe标点符号cool
3条回答

你可以这样过滤

orig = ["He", "is", "so", "", "cool"]
result = [x for x in orig if x]

或者可以使用filter。在python 3中,filter返回一个生成器,因此list()将其转换为一个列表。这在Python2.7中也适用

result = list(filter(None, orig))

您可以使用^{},使用None作为键函数,它过滤掉所有类似False的元素(包括空字符串)

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

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

Falseish值包括:

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

您可以使用列表理解:

cleaned = [x for x in your_list if x]

尽管我会使用regex来提取单词:

>>> import re
>>> sentence = 'This is some cool sentence with,    spaces'
>>> re.findall(r'(\w+)', sentence)
['This', 'is', 'some', 'cool', 'sentence', 'with', 'spaces']

相关问题 更多 >