您可以使用str.translate
过滤掉字母:
>>> from string import letters
>>> strs = "6483A2"
>>> strs.translate(None, letters)
'64832'
无需将字符串转换为列表,您可以遍历字符串本身。
使用str.join
,str.isdigit
和列表理解:
>>> ''.join([c for c in strs if c.isdigit()])
'64832'
或者这个你想要的sum
数字:
sum(int(c) for c in strs if c.isdigit())
时间比较:
小字符串:
>>> strs = "6483A2"
>>> %timeit sum(int(c) for c in strs.translate(None, letters))
100000 loops, best of 3: 9.19 us per loop
>>> %timeit sum(int(c) for c in strs if c.isdigit())
100000 loops, best of 3: 10.1 us per loop
大字符串:
>>> strs = "6483A2"*1000
>>> %timeit sum(int(c) for c in strs.translate(None, letters))
100 loops, best of 3: 5.47 ms per loop
>>> %timeit sum(int(c) for c in strs if c.isdigit())
100 loops, best of 3: 8.54 ms per loop
最坏情况,所有字母:
>>> strs = "A"*100
>>> %timeit sum(int(c) for c in strs.translate(None, letters))
100000 loops, best of 3: 2.53 us per loop
>>> %timeit sum(int(c) for c in strs if c.isdigit())
10000 loops, best of 3: 24.8 us per loop
>>> strs = "A"*1000
>>> %timeit sum(int(c) for c in strs.translate(None, letters))
100000 loops, best of 3: 7.34 us per loop
>>> %timeit sum(int(c) for c in strs if c.isdigit())
1000 loops, best of 3: 210 us per loop