LoginSignup
41
28

More than 5 years have passed since last update.

文字列を指定した文字数ごとに分割する。RubyとPythonで。

Last updated at Posted at 2015-08-28

はからずも最近Rubyを書いていて、Rubyだとこうかけるの知った

test.rb
s = '123456789'
v = s.each_char.each_slice(3).map(&:join)
# ['123', '456', '789']

かっこいい〜

Pythonだとこうでしょうか

test.py
s = '123456789'
v = [s[i: i+3] for i in range(0, len(s), 3)]
# ['123', '456', '789']

どっちがいいかと言われたら、個人的にはリスト内包表記とか汎用的な仕組みの組み合わせで出来るPythonのほうが好みだけど、 Rubyのほうが何してるかわかりやすい。いちいちメソッドがあるのすごい。

41
28
4

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
41
28