Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Python列表项中删除标点符号_Python_List - Fatal编程技术网

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

从Python列表项中删除标点符号,python,list,Python,List,我有一张这样的清单 ['hello', '...', 'h3.a', 'ds4,'] 这应该变成 ['hello', 'h3a', 'ds4'] 我只想删除标点符号,让字母和数字保持原样。 标点是字符串中的任何内容。标点是常量。 我知道这很简单,但我在python有点无所事事,所以 谢谢, giodamelio假设您的初始列表存储在变量x中,您可以使用: >>> x = [''.join(c for c in s if c not in string.punctuation

我有一张这样的清单

['hello', '...', 'h3.a', 'ds4,']
这应该变成

['hello', 'h3a', 'ds4']
我只想删除标点符号,让字母和数字保持原样。 标点是
字符串中的任何内容。标点是常量。
我知道这很简单,但我在python有点无所事事,所以

谢谢,
giodamelio

假设您的初始列表存储在变量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']
要创建新列表,请执行以下操作:

[re.sub(r'[^A-Za-z0-9]+', '', x) for x in list_of_strings]
ps st是字符串。因为清单是一样的

[''.join(x for x in par if x not in string.punctuation) for par in alist]
我认为效果很好。查看string.punctuaction:

>>> print string.punctuation
!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~
>打印字符串。标点符号
!"#$%&\'()*+,-./:;?@[\\]^_`{|}~
使用string.translate:

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

有关translate的文档,请参见python 3+中的

,请使用以下内容:

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

这不会对列表造成任何影响。+1因为我喜欢它,不知道translate可以在没有奇怪的translation表的情况下删除字符。
import string
s = s.translate(str.maketrans('','',string.punctuation))