如何删除单词或数字中间的标点符号?

Eri*_*iri 1 python punctuation

例如,如果我有一串数字和一个单词列表:

My_number = ("5,6!7,8")
My_word =["hel?llo","intro"]
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 5

使用str.translate:

>>> from string import punctuation
>>> lis = ["hel?llo","intro"]
>>> [ x.translate(None, punctuation) for x in lis]
['helllo', 'intro']
>>> strs = "5,6!7,8"
>>> strs.translate(None, punctuation)
'5678'
Run Code Online (Sandbox Code Playgroud)

使用regex:

>>> import re
>>> [ re.sub(r'[{}]+'.format(punctuation),'',x ) for x in lis]
['helllo', 'intro']
>>> re.sub(r'[{}]+'.format(punctuation),'', strs)
'5678'
Run Code Online (Sandbox Code Playgroud)

使用列表理解和str.join:

>>> ["".join([c for c in x if c not in punctuation])  for x in lis]
['helllo', 'intro']
>>> "".join([c for c in strs if c not in punctuation])
'5678'
Run Code Online (Sandbox Code Playgroud)

功能:

>>> from collections import Iterable
def my_strip(args):
    if isinstance(args, Iterable) and not isinstance(args, basestring):
        return [ x.translate(None, punctuation) for x in args]
    else:
        return args.translate(None, punctuation)
...     
>>> my_strip("5,6!7,8")
'5678'
>>> my_strip(["hel?llo","intro"])
['helllo', 'intro']
Run Code Online (Sandbox Code Playgroud)