33
31

More than 5 years have passed since last update.

Python3.6で導入されたフォーマット済み文字列リテラル(f'...')を使えばstr.format()より短く書ける

Last updated at Posted at 2017-12-13

この記事は Pythonのコードを短く簡潔に書くテクニック Advent Calendar 2017 の14日目です。

はじめに

Python3.6でフォーマット済み文字列リテラル(f-strings)というのが導入されました。
他の言語で変数埋め込みとか、変数展開とか、式展開と呼ばれているやつです。
これを使うとstr.format()を使わずに文字列中に変数の値や式を埋め込むことができます。

普通にstr.format()を使った場合

>>> a = 1
>>> b = 1.2345
>>> c = dict(key1=123)
>>> d = 'ABC'
>>> '{} {:.1f} {} {}'.format(a, b, c['key1'], d.lower())
'1 1.2 123 abc'

フォーマット済み文字列リテラルを使った場合

>>> a = 1
>>> b = 1.2345
>>> c = dict(key1=123)
>>> d = 'ABC'
>>> f'{a} {b:.1f} {c["key1"]} {d.lower()}'
'1 1.2 123 abc'

フォーマット済み文字列リテラルでは文字列中の{}の中に変数や式を書くことができます。
str.format()と同様に書式指定も可能です。

これでstr.format()よりだいぶ短く書くことができますが、シンタックスハイライトが対応していないとちょっとわかりにくいかも知れません。

参考

33
31
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
33
31