我想在python中删除字符串中的字符:

string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...

但我有很多字符必须删除。我想了一个清单

list = [',', '!', '.', ';'...]

但是如何使用列表来替换字符串中的字符呢?


当前回答

Python 3,单行列表综合实现。

from string import ascii_lowercase # 'abcdefghijklmnopqrstuvwxyz'
def remove_chars(input_string, removable):
  return ''.join([_ for _ in input_string if _ not in removable])

print(remove_chars(input_string="Stack Overflow", removable=ascii_lowercase))
>>> 'S O'

其他回答

另一种使用regex的方法:

''.join(re.split(r'[.;!?,]', s))

最近我在钻研scheme,现在我觉得我擅长递归和求值。哈哈哈。分享一些新的方法:

首先,求值

print eval('string%s' % (''.join(['.replace("%s","")'%i for i in replace_list])))

第二,递归

def repn(string,replace_list):
    if replace_list==[]:
        return string
    else:
        return repn(string.replace(replace_list.pop(),""),replace_list)

print repn(string,replace_list)

嘿,别投反对票。我只是想分享一些新的想法。

这个怎么样,一行字。

reduce(lambda x,y : x.replace(y,"") ,[',', '!', '.', ';'],";Test , ,  !Stri!ng ..")

在Python 3.8中,这适用于我:

s.translate(s.maketrans(dict.fromkeys(',!.;', '')))

也许有一种更现代、更实用的方式来实现你的愿望:

>>> subj = 'A.B!C?'
>>> list = set([',', '!', '.', ';', '?'])
>>> filter(lambda x: x not in list, subj)
'ABC'

请注意,对于这个特定的目的,它是相当夸张的,但一旦您需要更复杂的条件,过滤器就会派上用场