LoginSignup
18
20

More than 5 years have passed since last update.

Pythonの文字列フォーマット

Last updated at Posted at 2016-02-13

Pythonの文字列フォーマット

もういちいちドキュメント見るのが面倒なので必要なところだけメモ。

整列

  • 左詰め - {:<数字}
  • 右詰め - {:>数字}
  • 中央揃え - {:^数字}
  • 中央揃え with 詰め文字 - {:詰め文字^数字}
>>> '{:<30}'.format('left aligned')
'left aligned                  '
>>> '{:>30}'.format('right aligned')
'                 right aligned'
>>> '{:^30}'.format('centered')
'           centered           '
>>> '{:*^30}'.format('centered')
'***********centered***********'

進数

  • 十進数 - {:d}
  • 十六進数 - {:x} or {:#x}
  • 二進数 - {:b} or {:#b}
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

整数三桁セパレート

>>> "{:,}".format(1000000)
'1,000,000'

辞書オブジェクトの属性

>>> urldata = {"scheme":"http","netloc":"qiita.com","path":"/drafts"}
>>> url = "{scheme}://{netloc}{path}".format(urldata)

クラスの属性

0.が重要。

>>> url = "{0.scheme}://{0.netloc}{0.path}".format(urldata)

特殊な書式

>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'
18
20
0

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
18
20