从效率的角度来看,你打不败translate() - 它在C中使用查找表执行原始字符串操作 - 你自己的C代码没有太多可能可以击败它。如果不担心速度,另一个选择是:exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in exclude)
这比每个字符都要快,但是,不会像regex或string.translate那样的非纯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