Drkcore

03 06 2012 Python Tweet

Pythonのformatメソッド

いままでは、なんとなく慣れているという理由で昔ながらのformat(%dとか%s)を使っていたのだけど、最近stringのformatメソッドに切り替えたので、ドキュメントを読んでみた。

  • 7.1.3. Format String Syntax

文字列のなかで中括弧で挟んで埋め込みを指定するようになっている。conversionは現状repr(!r)かstr(!r)を指定できるようになっているがあまり使わないのでformat_specのほうを。

replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"

Format Specificationによると

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
fill        ::=  <a character other than '{' or '}'>
align       ::=  "<" | ">" | "=" | "^"
sign        ::=  "+" | "-" | " "
width       ::=  integer
precision   ::=  integer
type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

fillは埋め込む文字(デフォルトはspace)

30文字幅で中央寄せでtestという文字を埋め込み、空いてるところは"-"で埋める

>>> "{:-^30}".format("test")
'-------------test-------------'

alignは配置

<は左寄せ、>は右寄せ、^は中央寄せ。=はよくわからん。

signは正負の記号をどう表現するか

正数のときどう表示するかだな。

>>> "{:+05}".format(33)
'+0033'
>>> "{:+05}".format(-33)
'-0033'
>>> "{:-05}".format(33)
'00033'
>>> "{:-05}".format(-33)
'-0033'
>>> "{: 05}".format(33)
' 0033'
>>> "{: 05}".format(-33)
'-0033'

widthは幅で0からはじまる場合は空いてる部分は0で埋める。

>>> "{:05}".format(20)
'00020'

precisionが精度で、小数点以下じゃなくて全体で何桁って感じ。

>>> "{:10.5}".format(10/3.0)
'    3.3333'
>>> "{:10.5}".format(100/3.0)
'    33.333'

最後にfをつけると固定長表記

>>> "{:10.5f}".format(100/3.0)
'  33.33333'
>>> "{:10.5f}".format(10/3.0)
'   3.33333'

comma(,)は1000桁毎にカンマを打つオプションwidthとprecisionの間に入れる

>>> "{:10,}".format(123456789)
'123,456,789'

最後に型指定

  • b: バイナリ
  • c: キャラクタ
  • d: Decimal Integer
  • o: 8進数表記
  • x: 小文字の16進数表記
  • X: 大文字の16進数表記
  • e: 小文字の指数表記
  • E: 大文字の指数表記
  • f:固定長表記
  • g:一般的な表記(デフォルト)

結構素直な表記なので文法見ながら追っかけていったら大体理解できた。

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021