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