いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

Pythonメモ-24 (f文字列の書式メモ)(PEP498, フォーマット済み文字列リテラル, 数値フォーマット)

概要

python 3.6 で追加されたフォーマット済み文字列リテラル、通称 f-strings の書式について。

よく忘れるのでメモ。

内容

普通に内容表示

word = 'world'

f'hello {word}'
'hello world'

文字列長指定(デフォルト)

word = 'helloworld'

f'{word:20}'
'helloworld          '

文字列長指定(左寄せ)

word = 'helloworld'

f'{word:<20}'
'helloworld          '

文字列長指定(中央寄せ)

word = 'helloworld'

f'{word:^20}'
'     helloworld     '

文字列長指定(右寄せ)

word = 'helloworld'

f'{word:>20}'
'          helloworld'

文字列長指定(実際の文字列長より少ない値指定)

word = 'helloworld'

f'{word:5}'
'helloworld'

数値指定 (小数点以下桁数指定)

i = 123.4567

f'{i:.3f}'
'123.457'

数値指定(文字列長指定、小数点以下桁数指定)

i = 123.4567

f'{i:3.3f}'
'123.457'

数値指定(文字列長指定、実際より多い数、デフォルト)

i = 123.4567

f'{i:3.3f}'
'   123.457'

数値指定(ゼロ埋め)

i = 123.4567

f'{i:010.3f}'
'000123.457'

数値指定(ゼロ埋め、右寄せ)

i = 123.4567

f'{i:0>10.3f}'
'000123.457'

数値指定(ゼロ埋め、左寄せ)

i = 123.4567

f'{i:0<10.3f}'
'123.457000'

数値指定(ゼロ埋め、中央寄せ)

i = 123.4567

f'{i:0<10.3f}'
'0123.45700'

数値指定(16進数表現)

i = 123

f'{i:#0x}'
'0x7b'

日付指定

from datetime import datetime

now = datetime.now()

f'{now:%Y-%m-%d}'
'2017-10-24'

変換フィールド (!r, __repr__の呼び出し)

class sample:
  def __repr__(self):
    return 'call __repr__'

  def __str__(self):
    return 'call __str__'


obj = sample()

f'{obj!r}'
'call __repr__'

変換フィールド (!s, __str__の呼び出し)

class sample:
  def __repr__(self):
    return 'call __repr__'

  def __str__(self):
    return 'call __str__'


obj = sample()

f'{obj!s}'
'call __str__'

参考情報

2. 字句解析 — Python 3.7.3 ドキュメント

組み込み関数 — Python 3.7.3 ドキュメント

string --- 一般的な文字列操作 — Python 3.7.3 ドキュメント


過去の記事については、以下のページからご参照下さい。

サンプルコードは、以下の場所で公開しています。