23

例如我有一句话

"He is so .... cool!"

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

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

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

4

9 回答 9

50

您可以使用filter, withNone作为键函数,它过滤掉所有Falseish 元素(包括空字符串)

>>> 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
于 2013-04-19T07:42:30.990 回答
24

你可以像这样过滤它

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

或者你可以使用filter. 在 python 3filter中返回一个生成器,从而list()将它变成一个列表。这也适用于 python 2.7

result = list(filter(None, orig))
于 2013-04-19T07:41:51.187 回答
7

您可以使用列表推导:

cleaned = [x for x in your_list if x]

虽然我会使用正则表达式来提取单词:

>>> import re
>>> sentence = 'This is some cool sentence with,    spaces'
>>> re.findall(r'(\w+)', sentence)
['This', 'is', 'some', 'cool', 'sentence', 'with', 'spaces']
于 2013-04-19T07:43:31.647 回答
4

我会回答你应该问的问题——如何完全避免空字符串。我假设您执行以下操作来获取您的列表

>>> "He is so .... cool!".replace(".", "").split(" ")
['He', 'is', 'so', '', 'cool!']

关键是你.split(" ")用来分割空格字符。但是,如果您省略 的参数,则会split发生这种情况:

>>> "He is so .... cool!".replace(".", "").split()
['He', 'is', 'so', 'cool!']

引用文档:

如果 sep 未指定或为 None,则应用不同的拆分算法:连续空格的运行被视为单个分隔符,如果字符串具有前导或尾随空格,则结果将在开头或结尾不包含空字符串。

因此,您真的不需要为其他答案而烦恼(Blender 除外,这是一种完全不同的方法),因为 split 可以为您完成这项工作!

于 2013-04-19T07:47:58.380 回答
1
>>> from string import punctuation
>>> text = "He is so .... cool!"
>>> [w.strip(punctuation) for w in text.split() if w.strip(punctuation)]
['He', 'is', 'so', 'cool']
于 2013-04-19T07:43:01.340 回答
1

您可以使用列表推导非常轻松地过滤掉空字符串:

x = ["He", "is", "so", "", "cool"]
x = [str for str in x if str]
>>> ['He', 'is', 'so', 'cool']
于 2013-04-19T07:43:13.013 回答
1

Python 3 返回一个iteratorfrom filter,因此应该包含在对 list() 的调用中

str_list = list(filter(None, str_list)) # fastest
于 2019-09-30T18:47:45.543 回答
0
lst = ["He", "is", "so", "", "cool"]
lst = list(filter(str.strip, lst))
于 2020-11-02T13:44:18.703 回答
-1

您可以使用filter.

a = ["He", "is", "so", "", "cool"]
filter(lambda s: len(s) > 0, a)
于 2013-04-19T07:43:59.637 回答