2009年5月11日月曜日

pythonでsplit

文字列を一定のルールでちょん切って配列にするという仕事はよく生じる。
こんなときは、文字列にsplitメソッドを適用すればよい。

>>> "out of google, out of existence".split(" ")
['out', 'of', 'google,', 'out', 'of', 'existence']


でもsplitメソッドは、不定数の空白文字で区切られたものをうまく扱えない。

>>> "out of google, out of existence".split(" ")
['out', '', '', '', 'of', 'google,', 'out', 'of', '', '', 'existence']


perlだと正規表現を使ってsplitもできたのになあ、と不便に思って調べると、ちゃんとpythonでもそれができた。ただ、明示的に正規表現オブジェクトのメソッドとしてこれを使う。

>>> import re
>>> r1 = re.compile("\s+")
>>> r1.split("out of google, out of existence")
['out', 'of', 'google,', 'out', 'of', 'existence']


あらよかったね。

あと、例文には何の意味もありません。

0 コメント: