从字符串中删除一组字符

234
我想在Python中删除字符串中的字符:
我想在Python中删掉一个字符串中的某些字符:
string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...

但是我有许多字符需要删除。我考虑过一个列表。

list = [',', '!', '.', ';'...]
但是我该如何使用 list 来替换 string 中的字符呢?

6
请参考 https://dev59.com/a3I-5IYBdhLWcg3wTWj4,该网页提供了多种解决方案和精美的比较。 - Martijn de Milliano
很遗憾,Python(据说自带电池)没有直接处理这种用例的功能。PHP的函数str_replace可以做到 - 你可以将数组作为第一个参数传递,字符串作为第二个参数(http://php.net/manual/pl/function.str-replace.php)。 - JustAC0der
20个回答

4
也许更现代而且功能更强大的实现你所期望的方法是:
>>> subj = 'A.B!C?'
>>> list = set([',', '!', '.', ';', '?'])
>>> filter(lambda x: x not in list, subj)
'ABC'

请注意,对于这个特定的目的来说,这是一种过度杀伤力的方法,但是一旦需要更复杂的条件,过滤器就会很方便。

还要注意的是,这个操作也可以使用列表推导式来完成,我认为这种方式更符合Python的风格。 - rioted

4

另一个有趣的主题是从字符串中删除UTF-8重音字符,将字符转换为它们的标准无重音字符:

什么是在Python Unicode字符串中删除重音符号的最佳方法?

主题中的代码提取:

import unicodedata

def remove_accents(input_str):
    nkfd_form = unicodedata.normalize('NFKD', input_str)
    return u"".join([c for c in nkfd_form if not unicodedata.combining(c)])

2
这样如何——一行代码。
reduce(lambda x,y : x.replace(y,"") ,[',', '!', '.', ';'],";Test , ,  !Stri!ng ..")

2
在Python 3.8中,以下方法适用于我:
s.translate(s.maketrans(dict.fromkeys(',!.;', '')))

str.translate() 是Python2中的函数,不需要使用maketrans()函数。 - confiq
1
相反地,Python 3有一个str.translate()函数,它使用字符序号,因此需要str.maketrans()这样的东西(或类似于在其他Python 3答案中调用ord的dict comp)。如果没有maketrans(),这个答案将无法工作(请尝试)。 - 2e0byo

2
我认为这很简单,可以实现!
list = [",",",","!",";",":"] #the list goes on.....

theString = "dlkaj;lkdjf'adklfaj;lsd'fa'dfj;alkdjf" #is an example string;
newString="" #the unwanted character free string
for i in range(len(TheString)):
    if theString[i] in list:
        newString += "" #concatenate an empty string.
    else:
        newString += theString[i]

这是一种做法。但如果你厌倦了要保留一个你想要删除的字符列表,你可以通过使用字符串迭代的顺序号来实现。顺序号即该字符的ASCII值。数字0作为字符的ASCII码为48,小写字母z的ASCII码为122,因此:

theString = "lkdsjf;alkd8a'asdjf;lkaheoialkdjf;ad"
newString = ""
for i in range(len(theString)):
     if ord(theString[i]) < 48 or ord(theString[i]) > 122: #ord() => ascii num.
         newString += ""
     else:
        newString += theString[i]

1

我正在考虑这个问题的解决方案。首先,我会将字符串输入转换为列表。然后,我会替换列表中的项目。最后,通过使用join命令,我会将列表返回为字符串。代码可以如下:

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)

这将会从字符串中移除任何内容。你对此有什么看法?

1

这里是一个 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'

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


1

Why not utilize this simple function:

def remove_characters(str, chars_list):
    for char in chars_list:
        str = str.replace(char, '')
  
    return str

使用函数:

print(remove_characters('A.B!C?', ['.', '!', '?']))

输出:

ABC

1

最近我在深入学习Scheme,现在我觉得我擅长递归和求值。哈哈哈。分享一些新的方法:

首先,对其进行求值(eval)。

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)

嘿,不要点踩。我只是想分享一些新的想法。


1
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'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接