例如,我有一个句子
"He is so .... cool!"
Run Code Online (Sandbox Code Playgroud)
然后我删除所有标点符号并将其放入列表中.
["He", "is", "so", "", "cool"]
Run Code Online (Sandbox Code Playgroud)
如何删除或忽略空字符串?
Vol*_*ity 39
您可以使用filterwith None作为键函数,过滤掉所有Falseish的元素(包括空字符串)
>>> lst = ["He", "is", "so", "", "cool"]
>>> filter(None, lst)
['He', 'is', 'so', 'cool']
Run Code Online (Sandbox Code Playgroud)
但请注意,它filter返回Python 2中的列表,但是Python 3中的生成器.您需要将其转换为Python 3中的列表,或使用列表推导解决方案.
Falseish值包括:
False
None
0
''
[]
()
# and all other empty containers
Run Code Online (Sandbox Code Playgroud)
msv*_*kon 20
你可以像这样过滤它
orig = ["He", "is", "so", "", "cool"]
result = [x for x in orig if x]
Run Code Online (Sandbox Code Playgroud)
或者你可以使用filter.在python 3中filter返回一个生成器,从而list()将其转换为一个列表.这也适用于python 2.7
result = list(filter(None, orig))
Run Code Online (Sandbox Code Playgroud)
您可以使用列表理解:
cleaned = [x for x in your_list if x]
Run Code Online (Sandbox Code Playgroud)
虽然我会使用正则表达式来提取单词:
>>> import re
>>> sentence = 'This is some cool sentence with, spaces'
>>> re.findall(r'(\w+)', sentence)
['This', 'is', 'some', 'cool', 'sentence', 'with', 'spaces']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
61950 次 |
| 最近记录: |