4

私はPythonにかなり慣れていません。質問があります。たとえば、ファイルから行を読み取ると、次のような文字列があるとします。

thestring = '000,5\r\n'

この文字列からすべての非整数を削除してから、この文字列を整数自体に変換するにはどうすればよいですか? ありがとう!

4

1 に答える 1

11

を使用するstr.translateと、これがおそらく最速の方法です。

>>> strs = '000,5\r\n'    
>>> from string import ascii_letters, punctuation, whitespace
>>> ignore = ascii_letters + punctuation + whitespace
>>> strs.translate(None, ignore)
'0005'

使用regex:

>>> import re
>>> re.sub(r'[^\d]+','',strs)    #or re.sub(r'[^0-9]+','',strs)
'0005'

str.joinと の使用str.isdigit:

>>> "".join([x for x in strs  if x.isdigit()])
'0005'

int()整数を取得するために使用します。

>>> int('0005')
5

タイミング比較:

>>> strs = strs*10**4
>>> %timeit strs.translate(None, ignore)
1000 loops, best of 3: 441 us per loop

>>> %timeit re.sub(r'[^\d]+','',strs)
10 loops, best of 3: 20.3 ms per loop

>>> %timeit re.sub(r'[^0-9]+','',strs)
100 loops, best of 3: 17.1 ms per loop

>>> %timeit "".join([x for x in strs  if x.isdigit()])
10 loops, best of 3: 19.2 ms per loop
于 2013-06-18T20:16:22.613 に答える