226

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

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

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

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

但是如何使用list替换 中的字符string

4

20 回答 20

273

If you're using python2 and your inputs are strings (not unicodes), the absolutely best method is str.translate:

>>> chars_to_remove = ['.', '!', '?']
>>> subj = 'A.B!C?'
>>> subj.translate(None, ''.join(chars_to_remove))
'ABC'

Otherwise, there are following options to consider:

A. Iterate the subject char by char, omit unwanted characters and join the resulting list:

>>> sc = set(chars_to_remove)
>>> ''.join([c for c in subj if c not in sc])
'ABC'

(Note that the generator version ''.join(c for c ...) will be less efficient).

B. Create a regular expression on the fly and re.sub with an empty string:

>>> import re
>>> rx = '[' + re.escape(''.join(chars_to_remove)) + ']'
>>> re.sub(rx, '', subj)
'ABC'

(re.escape ensures that characters like ^ or ] won't break the regular expression).

C. Use the mapping variant of translate:

>>> chars_to_remove = [u'δ', u'Γ', u'ж']
>>> subj = u'AжBδCΓ'
>>> dd = {ord(c):None for c in chars_to_remove}
>>> subj.translate(dd)
u'ABC'

Full testing code and timings:

#coding=utf8

import re

def remove_chars_iter(subj, chars):
    sc = set(chars)
    return ''.join([c for c in subj if c not in sc])

def remove_chars_re(subj, chars):
    return re.sub('[' + re.escape(''.join(chars)) + ']', '', subj)

def remove_chars_re_unicode(subj, chars):
    return re.sub(u'(?u)[' + re.escape(''.join(chars)) + ']', '', subj)

def remove_chars_translate_bytes(subj, chars):
    return subj.translate(None, ''.join(chars))

def remove_chars_translate_unicode(subj, chars):
    d = {ord(c):None for c in chars}
    return subj.translate(d)

import timeit, sys

def profile(f):
    assert f(subj, chars_to_remove) == test
    t = timeit.timeit(lambda: f(subj, chars_to_remove), number=1000)
    print ('{0:.3f} {1}'.format(t, f.__name__))

print (sys.version)
PYTHON2 = sys.version_info[0] == 2

print ('\n"plain" string:\n')

chars_to_remove = ['.', '!', '?']
subj = 'A.B!C?' * 1000
test = 'ABC' * 1000

profile(remove_chars_iter)
profile(remove_chars_re)

if PYTHON2:
    profile(remove_chars_translate_bytes)
else:
    profile(remove_chars_translate_unicode)

print ('\nunicode string:\n')

if PYTHON2:
    chars_to_remove = [u'δ', u'Γ', u'ж']
    subj = u'AжBδCΓ'
else:
    chars_to_remove = ['δ', 'Γ', 'ж']
    subj = 'AжBδCΓ'

subj = subj * 1000
test = 'ABC' * 1000

profile(remove_chars_iter)

if PYTHON2:
    profile(remove_chars_re_unicode)
else:
    profile(remove_chars_re)

profile(remove_chars_translate_unicode)

Results:

2.7.5 (default, Mar  9 2014, 22:15:05) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)]

"plain" string:

0.637 remove_chars_iter
0.649 remove_chars_re
0.010 remove_chars_translate_bytes

unicode string:

0.866 remove_chars_iter
0.680 remove_chars_re_unicode
1.373 remove_chars_translate_unicode

---

3.4.2 (v3.4.2:ab2c023a9432, Oct  5 2014, 20:42:22) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]

"plain" string:

0.512 remove_chars_iter
0.574 remove_chars_re
0.765 remove_chars_translate_unicode

unicode string:

0.817 remove_chars_iter
0.686 remove_chars_re
0.876 remove_chars_translate_unicode

(As a side note, the figure for remove_chars_translate_bytes might give us a clue why the industry was reluctant to adopt Unicode for such a long time).

于 2012-04-04T18:29:58.297 回答
117

You can use str.translate():

s.translate(None, ",!.;")

Example:

>>> s = "asjo,fdjk;djaso,oio!kod.kjods;dkps"
>>> s.translate(None, ",!.;")
'asjofdjkdjasooiokodkjodsdkps'
于 2012-04-04T18:31:22.453 回答
36

You can use the translate method.

s.translate(None, '!.;,')
于 2012-04-04T18:31:32.230 回答
28

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

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

这是一个使用示例:

>>> list = [',', '!', '.', ';']
>>> s = "This is, my! str,ing."
>>> s.translate({ord(x): '' for x in list})
'This is my string'
于 2016-09-11T12:33:47.343 回答
18
''.join(c for c in myString if not c in badTokens)
于 2012-04-04T18:53:30.953 回答
10

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

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

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

于 2013-10-23T07:47:04.970 回答
9

使用正则表达式的另一种方法:

''.join(re.split(r'[.;!?,]', s))
于 2012-04-04T18:51:41.867 回答
6

you could use something like this

def replace_all(text, dic):
  for i, j in dic.iteritems():
    text = text.replace(i, j)
  return text

This code is not my own and comes from here its a great article and dicusses in depth doing this

于 2012-04-04T18:31:25.183 回答
5

简单的方法,

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)

输出:

this-is-string--foo----bar--tuna---sandwich--is---good

于 2016-12-22T19:55:34.793 回答
4

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

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

请注意,对于这个特定的目的,这有点过头了,但是一旦您需要更复杂的条件,过滤器就会派上用场

于 2015-03-24T17:20:34.387 回答
4

还有一个有趣的主题是删除 UTF-8 重音形式的字符串,将 char 转换为标准的非重音字符:

在 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)])
于 2014-05-31T07:23:24.667 回答
3

消除 *%,&@!从下面的字符串:

s = "this is my string,  and i will * remove * these ** %% "
new_string = s.translate(s.maketrans('','','*%,&@!'))
print(new_string)

# output: this is my string  and i will  remove  these  
于 2020-05-26T08:01:40.397 回答
2

在 Python 3.8 中,这对我有用:

s.translate(s.maketrans(dict.fromkeys(',!.;', '')))
于 2021-12-03T09:52:20.497 回答
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 作为 char 的 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]
于 2016-11-13T15:45:53.403 回答
2

这个怎么样 - 一个班轮。

reduce(lambda x,y : x.replace(y,"") ,[',', '!', '.', ';'],";Test , ,  !Stri!ng ..")
于 2015-11-03T04:13:28.153 回答
1

这些天我正在研究计划,现在我认为擅长递归和评估。哈哈哈。只是分享一些新方法:

首先,评估它

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)

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

于 2013-10-28T14:23:44.350 回答
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)

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

于 2015-05-26T04:00:01.257 回答
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'
于 2020-05-08T03:38:41.510 回答
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'

在这里,我们拆分在 中找到的项目blacklist,展平结果并加入字符串。

于 2018-02-09T01:31:07.913 回答
0

为什么不利用这个简单的功能:

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

使用功能:

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

输出:

ABC
于 2022-02-02T15:53:58.920 回答