2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

python3.6以上ならformatよりf-stringsが便利

Posted at

python3で文字列に何かを追加するときはformatを使っていたけれど、f-stringのほうが簡潔かつ可読性高く、しかも10倍は処理が速くて良いです。知ったきっかけはこの記事。ほかにも便利な機能紹介が盛りだくさんでおすすめです。

使い方

formatf-stringsの使い方を並べます。
f-stringsf'文字列{挿入}'と単純明快。

import emoji


oracle = emoji.emojize(':eyes:')
dragon = emoji.emojize(':dragon:')

proverb = '{}{}を欠く'.format(dragon, oracle)
f_proverb = f'{dragon}{oracle}を欠く'

# 🐉👀を欠く

速度比較

colaboratoryの%timeitマジックで調べたところ、10倍の差をつけてf-stringsが高速でした。

speed_test
%timeit proverb = '{}{}を欠く'.format(dragon, oracle)
%timeit f_proverb = f'{dragon}{oracle}を欠く'

# 1000000 loops, best of 3: 329 ns per loop
# 10000000 loops, best of 3: 27.7 ns per loop
2
1
1

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?