どこかに向かうらしい話

迷走エンジニアの放浪記

Python3におけるformat形式を自分のためにまとめてみた件

主なネタはココにある通り。
http://docs.python.jp/3.5/library/string.html#formatspec

自分がよく使うパターンに絞ってメモしてみる。

>>> printf("hoge")
hoge(改行あり)
>>> print("hoge", end="")
hoge(改行なし)

ポジション引数を使ったアクセス:

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{0} {1} {0}'.format('abra', 'cad')   # 引数のインデクスは繰り返すことができます
'abra cad abra'

引数の要素へのアクセス:

>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'

テキストの幅を指定した整列:

>>> '{:<30}'.format('left aligned')
'left aligned                  '
>>> '{:>30}'.format('right aligned')
'                 right aligned'
>>> '{:^30}'.format('centered')
'           centered           '
>>> '{:*^30}'.format('centered')  # 詰め文字に '*' を使う
'***********centered***********'

%+f と %-f, % f の置換、そして符号の指定:

>>> '{:+f}; {:+f}'.format(3.14, -3.14)  # 常に表示する
'+3.140000; -3.140000'
>>> '{:f}; {:f}'.format(3.14, -3.14)  # 正の数にはスペースを表示
'3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14)  # マイナスだけを表示 -- '{:f}; {:f}' と同じ
'3.140000; -3.140000'

dによる指定:

>>> print("{0:d}".format(123))
123
>>> print("{0:+d}".format(123))
+123
>>> print("{0:04d}".format(123))
0123
>>> print("{0:+04d}".format(123))
+123
>>> print("{0:06d}".format(123))
000123
>>> print("{0:+06d}".format(123))
+00123

固定小数点の出力に関する指定:

標準では以下の通り。

>>> print("{0:f}".format(12.3456))
12.345600

小数点の位置に注目。

>>> print("{0:.1f}".format(12.3456))
12.3
>>> print("{0:.2f}".format(12.3456))
12.35
>>> print("{0:.3f}".format(12.3456))
12.346
>>> print("{0:.4f}".format(12.3456))
12.3456
>>> print("{0:.5f}".format(12.3456))
12.34560

小数点と表示させる桁数の比較。 x.yfは、小数点y桁だけ必ず表示しつつ、x文字分の表示領域に収めるように出力される。 (小数点も1文字としてカウントする)
ただし、出力対象がx文字分の表示領域に収まらない場合は、その分はオーバーして出力される。

>>> print("{0:3.1f}".format(12.3456))      # 小数点1桁必ず表示しつつ、3文字分の表示領域に収めるように出力されるが、表示領域に収まらないため、その分はオーバーして出力される。
12.3
>>> print("{0:4.1f}".format(12.3456))      # 小数点1桁必ず表示しつつ、4文字分の表示領域に収めるように出力される。
12.3
>>> print("{0:5.1f}".format(12.3456))      # 小数点1桁必ず表示しつつ、5文字分の表示領域に収めるように出力される。
 12.3
>>> print("{0:6.1f}".format(12.3456))      # 小数点1桁必ず表示しつつ、6文字分の表示領域に収めるように出力される。
  12.3
>>> print("{0:4.2f}".format(12.3456))      # 小数点2桁必ず表示しつつ、4文字分の表示領域に収めるように出力されるが、表示領域に収まらないため、その分はオーバーして出力される。
12.35
>>> print("{0:5.2f}".format(12.3456))      # 小数点2桁必ず表示しつつ、5文字分の表示領域に収めるように出力される。
12.35
>>> print("{0:6.2f}".format(12.3456))      # 小数点2桁必ず表示しつつ、6文字分の表示領域に収めるように出力される。
 12.35
>>> print("{0:7.2f}".format(12345.6789))   # 小数点2桁必ず表示しつつ、7文字分の表示領域に収めるように出力されるが、表示領域に収まらないため、その分はオーバーして出力される。
12345.68
>>> print("{0:8.2f}".format(12345.6789))   # 小数点2桁必ず表示しつつ、8文字分の表示領域に収めるように出力される。
12345.68
>>> print("{0:9.2f}".format(12345.6789))   # 小数点2桁必ず表示しつつ、9文字分の表示領域に収めるように出力される。
 12345.68