删除字符串中的字符列表

Lau*_*ura 210 python string replace list

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

string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...
Run Code Online (Sandbox Code Playgroud)

但是我必须删除许多字符.我想到了一个清单

list = [',', '!', '.', ';'...]
Run Code Online (Sandbox Code Playgroud)

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

geo*_*org 257

如果您使用的是python2并且您的输入是字符串(不是unicodes),那么绝对最好的方法是str.translate:

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

否则,有以下选项可供考虑:

A.通过char迭代主题char,省略不需要的字符和join结果列表:

>>> sc = set(chars_to_remove)
>>> ''.join([c for c in subj if c not in sc])
'ABC'
Run Code Online (Sandbox Code Playgroud)

(请注意,生成器版本''.join(c for c ...)效率较低).

B.动态创建正则表达式并re.sub使用空字符串:

>>> import re
>>> rx = '[' + re.escape(''.join(chars_to_remove)) + ']'
>>> re.sub(rx, '', subj)
'ABC'
Run Code Online (Sandbox Code Playgroud)

(re.escape确保字符喜欢^]不会破坏正则表达式).

C.使用以下映射变体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'
Run Code Online (Sandbox Code Playgroud)

完整的测试代码和时间:

#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)
Run Code Online (Sandbox Code Playgroud)

结果:

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
Run Code Online (Sandbox Code Playgroud)

(作为旁注,这个数字remove_chars_translate_bytes可能会让我们知道为什么业界不愿意长期采用Unicode).

  • 第二种方法会引发错误“TypeError: translate() 只需要一个参数(给定的 2 个)”。显然它以 dict 作为参数。 (2认同)

Sve*_*ach 109

你可以使用str.translate():

s.translate(None, ",!.;")
Run Code Online (Sandbox Code Playgroud)

例:

>>> s = "asjo,fdjk;djaso,oio!kod.kjods;dkps"
>>> s.translate(None, ",!.;")
'asjofdjkdjasooiokodkjodsdkps'
Run Code Online (Sandbox Code Playgroud)

  • @ thg435:没有人要求这个,但无论如何:`s.translate(dict.fromkeys(map(ord,u",!!."))) (19认同)
  • 为什么python3:TypeError:translate()只接受一个参数(给定2个) (7认同)
  • 这个(和@ PraveenGollakota的)[同时回答](http://stackoverflow.com/a/10017200/623735)正是@Laura所要求的,应该是首选的答案. (2认同)
  • @Gank:`unicode.translate()`方法与`str.translate()`方法有不同的参数.对于Unicode对象,请使用上述注释中的变体. (2认同)

Pra*_*ota 35

您可以使用translate方法.

s.translate(None, '!.;,')
Run Code Online (Sandbox Code Playgroud)


nin*_*cko 15

''.join(c for c in myString if not c in badTokens)
Run Code Online (Sandbox Code Playgroud)


Dek*_*kel 9

如果您正在使用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'
Run Code Online (Sandbox Code Playgroud)


ala*_*lan 8

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

''.join(re.split(r'[.;!?,]', s))
Run Code Online (Sandbox Code Playgroud)


kry*_*our 6

你可以使用这样的东西

def replace_all(text, dic):
  for i, j in dic.iteritems():
    text = text.replace(i, j)
  return text
Run Code Online (Sandbox Code Playgroud)

这段代码不是我自己的,它来自这里是一篇很棒的文章,深入讨论这个问题


aIK*_*Kid 6

为什么不是简单的循环?

for i in replace_list:
    string = string.replace(i, '')
Run Code Online (Sandbox Code Playgroud)

另外,请避免命名列表'列表'.它会覆盖内置函数list.


per*_*o25 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)
Run Code Online (Sandbox Code Playgroud)

输出:

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


Bip*_*Das 5

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

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  
Run Code Online (Sandbox Code Playgroud)