Help us understand the problem. What is going on with this article?

Python3のstr.format()メソッドのいろんな書式指定

More than 3 years have passed since last update.

改めてstr.format()メソッドのリファレンスを見直したのでいろいろメモ。

テキストの幅指定

:の後に桁数を指定する。:と数字の間に`<, >, ^'のいずれかを入れると文字揃えも指定できる。

>>> '{:30}'.format('30chars')           # デフォルトは左揃え
'30chars                       '
>>> '{:<30}'.format('left aligned')     # '<'をつけると左揃え
'left aligned                  '
>>> '{:>30}'.format('right aligned')    # '>'をつけると右揃え
'                 right aligned'
>>> '{:^30}'.format('centered')         # '^'をつけると中央揃え
'           centered           '
>>> '{:*^30}'.format('centered')        # 文字揃えの指定の前においた文字で空白を埋める
'***********centered***********'

数値の指定いろいろ

>>> '{:+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)  # '-'の場合、負のみ符号を表示
'3.140000; -3.140000'
>>> '{:.4f}; {:.4f}'.format(3.14, -3.14)    # '.'に続けて小数点以下の桁数を指定
'3.1400; -3.1400'
>>> '{:,}'.format(1234567890)   # 3桁ずつでカンマ区切り
'1,234,567,890'
>>> 
>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points / total)    # パーセントで表示
'Correct answers: 86.36%'

底の変換

:の後にd, x, o, bのいずれかを指定する。#をつけると接頭辞表示。

記号 変換先
d 10進数
x 16進数
o 8進数
b 2進数
>>> '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'

日付のフォーマット

>>> import datetime
>>> d = datetime.datetime.now()
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2016-03-17 17:33:11'
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした