数字の文字列を左に0で埋める、つまり、数字の文字列が特定の長さになるようにする最もピシッとした方法は何ですか?
弦楽器。
>>> n = '4'
>>> print(n.zfill(3))
004
また、数字に対しては
>>> n = 4
>>> print('%03d' % n)
004
>>> print(format(n, '03')) # python >= 2.6
004
>>> print('{0:03d}'.format(n)) # python >= 2.6 + python 3
004
>>> print('{foo:03d}'.format(foo=n)) # python >= 2.6 + python 3
004
>>> print('{:03d}'.format(n)) # python >= 2.7 + python3
004
>>> print(f'{n:03}') # python >= 3.6
004
文字列フォーマットのドキュメントを参照してください。
zfill`以外にも、一般的な文字列の書式設定を行うことができます。
print(f'{number:05d}') # (since Python 3.6), or
print('{:05d}'.format(number)) # or
print('{0:05d}'.format(number)) # or (explicit 0th positional arg. selection)
print('{n:05d}'.format(n=number)) # or (explicit `n` keyword arg. selection)
print(format(number, '05d'))
string formatting](http://docs.python.org/library/string.html#string-formatting) と f-strings のドキュメントです。
width = 10
x = 5
print "%0*d" % (width, x)
> 0000000005
詳細については、印刷ドキュメントをご覧ください。
Python 3.x (7.5年後)のためのアップデート
この最後の行は、今では
print("%0*d" % (width, x))
つまり、print()
は今ではステートメントではなく、関数になっています。なお、私はいまだにオールドスクールの printf()
スタイルを好んで使っていますが、それは IMNSHO の方が読みやすいということと、1980 年 1 月からこの記法を使っているからです。何か......老犬......何か......新しいトリック。