LoginSignup
4
3

More than 5 years have passed since last update.

PythonとRubyのsplit

Last updated at Posted at 2017-03-09

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", "", "", ""]

参考

4
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3