从Python列表项中删除标点符号

时间:2010-12-06 21:42:52

标签: python list

我有一个像

这样的清单
['hello', '...', 'h3.a', 'ds4,']

这应该变成

['hello', 'h3a', 'ds4']

我想只删除字母和数字完整的标点符号。 标点符号是string.punctuation常量中的任何内容。 我知道这很简单,但我在python中有点不知所以......

谢谢, giodamelio

5 个答案:

答案 0 :(得分:18)

假设您的初始列表存储在变量x中,您可以使用:

>>> x = [''.join(c for c in s if c not in string.punctuation) for s in x]
>>> print(x)
['hello', '', 'h3a', 'ds4']

删除空字符串:

>>> x = [s for s in x if s]
>>> print(x)
['hello', 'h3a', 'ds4']

答案 1 :(得分:8)

使用string.translate:

>>> import string
>>> test_case = ['hello', '...', 'h3.a', 'ds4,']
>>> [s.translate(None, string.punctuation) for s in test_case]
['hello', '', 'h3a', 'ds4']

有关翻译的文档,请参阅http://docs.python.org/library/string.html

答案 2 :(得分:1)

制作新名单:

[re.sub(r'[^A-Za-z0-9]+', '', x) for x in list_of_strings]

答案 3 :(得分:1)

import string

print ''.join((x for x in st if x not in string.punctuation))

ps st是字符串。列表是相同的......

[''.join(x for x in par if x not in string.punctuation) for par in alist]

我认为效果很好。看看string.punctuaction:

>>> print string.punctuation
!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~

答案 4 :(得分:0)

在python 3+中,请改用它:

import string
s = s.translate(str.maketrans('','',string.punctuation))