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

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

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

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

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


当前回答

简单的方法,

import re
str = 'this is string !    >><< (foo---> bar) @-tuna-#   sandwich-%-is-$-* good'

// condense multiple empty spaces into 1
str = ' '.join(str.split()

// replace empty space with dash
str = str.replace(" ","-")

// take out any char that matches regex
str = re.sub('[!@#$%^&*()_+<>]', '', str)

输出:

这是细绳,foo,酒吧,金枪鱼三明治——是——好

其他回答

下面是more_itertools的方法:

import more_itertools as mit


s = "A.B!C?D_E@F#"
blacklist = ".!?_@#"

"".join(mit.flatten(mit.split_at(s, pred=lambda x: x in set(blacklist))))
# 'ABCDEF'

在这里,我们将在黑名单中找到的项目进行拆分,将结果平直并连接字符串。

为什么不是一个简单的循环?

for i in replace_list:
    string = string.replace(i, '')

另外,避免将列表命名为“list”。它覆盖内置函数列表。

如果您正在使用python3并寻找翻译解决方案-函数已更改,现在接受1个参数而不是2个参数。

该参数是一个表(可以是字典),其中每个键都是要查找的字符的Unicode序数(int),值是替换值(可以是要将键映射到的Unicode序数或字符串)。

下面是一个用法示例:

>>> list = [',', '!', '.', ';']
>>> s = "This is, my! str,ing."
>>> s.translate({ord(x): '' for x in list})
'This is my string'

我在想一个解决办法。首先,我将字符串输入作为一个列表。然后我将替换列表中的项。然后通过join命令,我将返回list作为字符串。代码可以是这样的:

def the_replacer(text):
    test = []    
    for m in range(len(text)):
        test.append(text[m])
        if test[m]==','\
        or test[m]=='!'\
        or test[m]=='.'\
        or test[m]=='\''\
        or test[m]==';':
    #....
            test[n]=''
    return ''.join(test)

这将删除字符串中的任何内容。你怎么看?

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

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

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