1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

print()文の書式設定覚書(書きかけ)

Last updated at Posted at 2019-06-30

print文による書式設定

%を使う方法

以下の型に対応する

指定 データ型
%s 文字列
%d 10進整数
%x 16進整数
%o 8進整数
%f 10進float
%e 指数形式float
%g 10進floatまたは指数形式float
%% %
>>> print('%d' % 100)
100
>>> print('%f' % 100)
100.000000
>>> print('%e' % 100)
1.000000e+02

複数の変数を用いる場合は、タプルで与える(括弧が必要)

>>> print('%s is %d years old.' % ('Eri', 18))
Eri is 18 years old.

以下のようにすると幅の下限、文字列の上限、左寄せを指定できる。まずデフォルトでは以下のように表示される

>>> import math
>>> d = 10
>>> e = math.e
>>> s = 'apple pineapple pen'
>>> print('%d|%f|%s' % (d, e, s))
10|2.718282|apple pineapple pen

数字を指定すると最小幅指定となり、その幅に満たない場合はスペースで埋められ、それより長い場合はそのまま。

>>> print('%10d|%10f|%10s' % (d, e, s))
        10|  2.718282|apple pineapple pen

-を用いて左寄せにした

>>> print('%-10d|%-10f|%-10s' % (d, e, s))
10        |2.718282  |apple pineapple pen

.のあとに数字を書くと文字数の上限となり、それに満たない数字は0で埋められ、少数はその桁数に制限され、文字はその文字数に制限される

>>> print('%.5d|%.5f|%.5s' % (d, e, s))
00010|2.71828|apple

幅の下限、文字数の上限を同時に定めるとこうなる

>>> print('%6.5d|%6.5f|%6.5s' % (d, e, s))
 00010|2.71828| apple

幅の下限を文字数の上限より小さく指定したときは、指定しない場合と同じ

>>> print('%3.5d|%3.5f|%3.5s' % (d, e, s))
00010|2.71828|apple

文字数のそれぞれの指定は、変数で与えることも可能

>>> print('%*.*d|%*.*f|%*.*s|' % (0, 4, d, 6, 3, e, 0, 100, s))
0010| 2.718|apple pineapple pen|

{}を使う方法

Python3から可能になった方法。こちらの書式では変数の順序を指定したり、繰り返し用いたりできる

1
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?