LoginSignup
0
1

More than 5 years have passed since last update.

rubyとpython数字をゼロで詰めるには:rubyとpythonの両方

Last updated at Posted at 2018-09-20

rubyやpythonで数字をゼロで詰めたいときがあります。

たとえば8桁を用意して数字が4桁のとき、左側にゼロを4個出力するとかです。

00001234

のように出力したい。

rubyの場合

rubyにはCのsprintf関数のようなメソッドがあって

str = sprintf("%08d", i)

のように使えます。

rubyのインタープリターirbで実行しました。

irb(main):001:0> i=1234
=> 1234
irb(main):002:0> sprintf("%08d", i)
=> "00001234"

ほかにも便利と思ったら

str = "%08d" % i

の方法もありました。

こっちのほうがrubyっぽいですかね。

irb(main):015:0> "%08d" % i
=> "00001234"

Pythonの場合

Pythonは、zfillメソッドが使えます。

i = 1234

としたあと、iを文字列に変換して

str(i).zfill(8)
str(i).zfill(8)

とします。

Python3インタープリターで見てみます。

>>> i=1234
>>> print(str(i).zfill(8))
00001234
0
1
3

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
0
1