2013-03-22 16 views
9

私はこのような文字列を処理しています:"125A12C15" 文字と数字の境界で分割する必要があります。これは["125","A","12","C","15"]になります。文字列内の数字から文字を分割する

これをPythonで行うには、位置によって位置を変え、文字か数字かをチェックし、それに応じて連結するよりエレガントな方法がありますか?例えば。この種のもののための組み込み関数またはモジュール?

ありがとうございました! Lastalda

+0

次の(SO)記事はあなたの質問に正確に答えます;)http://stackoverflow.com/questions/3340081/product-code-looks-like-abcd2343-what-to-split-by-letters-and -numbers gr、M. – Michael

答えて

26

使用itertools.groupby一緒str.isalpha方法に:

ドキュメント文字列:

GROUPBY(反復可能【、keyfunc]) - >によってグループ化 (キー、サブイテレータ)を返すイテレータを作成しますkey(value)の各値


ドキュメンテーション文字列:

S.isalpha() - > BOOL

trueを返し、偽S内のすべての文字が アルファベットであり、Sに少なくとも1つの文字があればさもないと。

regular expressions moduleから

In [1]: from itertools import groupby 

In [2]: s = "125A12C15" 

In [3]: [''.join(g) for _, g in groupby(s, str.isalpha)] 
Out[3]: ['125', 'A', '12', 'C', '15'] 

または可能性re.findallまたはre.split:パフォーマンスについては

In [4]: import re 

In [5]: re.findall('\d+|\D+', s) 
Out[5]: ['125', 'A', '12', 'C', '15'] 

In [6]: re.split('(\d+)', s) # note that you may have to filter out the empty 
           # strings at the start/end if using re.split 
Out[6]: ['', '125', 'A', '12', 'C', '15', ''] 

In [7]: re.split('(\D+)', s) 
Out[7]: ['125', 'A', '12', 'C', '15'] 

、正規表現を使用すると、おそらく高速であるようだ。

In [8]: %timeit re.findall('\d+|\D+', s*1000) 
100 loops, best of 3: 2.15 ms per loop 

In [9]: %timeit [''.join(g) for _, g in groupby(s*1000, str.isalpha)] 
100 loops, best of 3: 8.5 ms per loop 

In [10]: %timeit re.split('(\d+)', s*1000) 
1000 loops, best of 3: 1.43 ms per loop 
+0

「re.findall」はうまく動作します、ありがとうございます! – Lastalda