我们有一组字符串,例如:c1309IF1306v1309p1209a1309mo1309
在Python中,去除数字的最佳方法是什么?我只需要上面的例子:cIFvpamo

最佳答案

您可以使用regex

>>> import re
>>> strs = "c1309, IF1306, v1309, p1209, a1309, mo1309"
>>> re.sub(r'\d','',strs)
'c, IF, v, p, a, mo'

或更快的版本:
>>> re.sub(r'\d+','',strs)
'c, IF, v, p, a, mo'

timeit比较:
>>> strs = "c1309, IF1306, v1309, p1209, a1309, mo1309"*10**5

>>> %timeit re.sub(r'\d','',strs)
1 loops, best of 3: 1.23 s per loop

>>> %timeit re.sub(r'\d+','',strs)
1 loops, best of 3: 480 ms per loop

>>> %timeit ''.join([c for c in strs if not c.isdigit()])
1 loops, best of 3: 1.07 s per loop

#winner
>>> %timeit from string import digits;strs.translate(None, digits)
10 loops, best of 3: 20.4 ms per loop

10-05 21:29