从效率的角度看,你不会打败s.translate(None, string.punctuation)

对于Python的更高版本,请使用以下代码:

s.translate(str.maketrans('', '', string.punctuation))

它使用一个查找表在C中执行原始字符串操作-除了编写自己的C代码之外,没有什么可以克服的。

如果速度不是问题,另一个选择是:

exclude = set(string.punctuation)s = ''.join(ch for ch in s if ch not in exclude)

这比用每个字符替换的速度要快,但不会像正则表达式或string.转换这样的非纯python方法执行得那么好,正如您从下面的时间表中可以看到的那样。对于这种类型的问题,在尽可能低的水平上去做是有回报的。

计时码:

import re, string, timeit
s = "string. With. Punctuation"
exclude = set(string.punctuation)
table = string.maketrans("","")
regex = re.compile('[%s]' % re.escape(string.punctuation))
def test_set(s):
return ''.join(ch for ch in s if ch not in exclude)
def test_re(s): # From Vinko's solution, with fix.
return regex.sub('', s)
def test_trans(s):
return s.translate(table, string.punctuation)
def test_repl(s): # From S.Lott's solution
for c in string.punctuation:
s=s.replace(c,"")
return s
print "sets :",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000)
print "regex :",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000)
print "translate :",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000)
print "replace :",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000)

结果如下:

sets : 19.8566138744

regex : 6.86155414581

translate : 2.12455511093

replace : 28.4436721802