Edited at

PythonとRubyのsplit

More than 1 year has passed since last update.

Pythonのsplitの挙動


Python

>>> ',,,1,2,3,,,4,5,,,'.split(',')

['', '', '', '1', '2', '3', '', '', '4', '5', '', '', '']


は直感通りだが、これと同じ感覚でRubyのsplitを使うと末尾に連続する空要素が除去され、ハマる。


Ruby

> ',,,1,2,3,,,4,5,,,'.split(',')

=> ["", "", "", "1", "2", "3", "", "", "4", "5"]

Pythonと同様の挙動にしたいときは-1を渡すとよい。


Ruby

> ',,,1,2,3,,,4,5,,,'.split(',',-1)

=> ["", "", "", "1", "2", "3", "", "", "4", "5", "", "", ""]

参考