我有一个清单
['hello', '...', 'h3.a', 'ds4,']
Run Code Online (Sandbox Code Playgroud)
这应该变成了
['hello', 'h3a', 'ds4']
Run Code Online (Sandbox Code Playgroud)
我想只删除字母和数字完整的标点符号.标点符号是string.punctuation常量中的任何内容.我知道这很简单,但我在python中有点noobie所以......
谢谢,giodamelio
Mar*_*ers 20
假设您的初始列表存储在变量x中,您可以使用:
>>> x = [''.join(c for c in s if c not in string.punctuation) for s in x]
>>> print(x)
['hello', '', 'h3a', 'ds4']
Run Code Online (Sandbox Code Playgroud)
要删除空字符串:
>>> x = [s for s in x if s]
>>> print(x)
['hello', 'h3a', 'ds4']
Run Code Online (Sandbox Code Playgroud)
使用string.translate:
>>> import string
>>> test_case = ['hello', '...', 'h3.a', 'ds4,']
>>> [s.translate(None, string.punctuation) for s in test_case]
['hello', '', 'h3a', 'ds4']
Run Code Online (Sandbox Code Playgroud)
有关翻译的文档,请参阅http://docs.python.org/library/string.html