1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

f-string vs format vs %:Python の文字列フォーマット比較

Posted at

Pythonで文字列を構築する場面は日常的に訪れます。その際に登場するのが、文字列フォーマットの3つの代表的な方法:

  • % 演算子による古典的なフォーマット
  • str.format() による柔軟なメソッド形式
  • f-string(フォーマット済み文字列リテラル)による最新のシンタックス(Python 3.6以降)

それぞれに一長一短があり、どれを使うべきか迷う場面もあるでしょう。

各フォーマット方法の基本構文

1. % 演算子

C言語由来の伝統的なスタイルです。

name = "Alice"
age = 30
print("My name is %s and I am %d years old." % (name, age))
  • メリット:短く書ける、Python 2 でも使用可能
  • デメリット:型指定(%s, %dなど)ミスがエラーに繋がりやすい

2. str.format() メソッド

Python 2.7 / 3.x 以降でサポートされている汎用的な方法です。

print("My name is {} and I am {} years old.".format(name, age))
  • メリット:名前付き引数や順番の制御が可能
  • デメリット:やや冗長で長くなりがち
print("My name is {name} and I am {age} years old.".format(name="Alice", age=30))

3. f-string(Python 3.6+)

もっともモダンで人気の高い方法です。

print(f"My name is {name} and I am {age} years old.")
  • メリット:簡潔で直感的、式評価も可能
  • デメリット:Python 3.6 以上でのみ使用可能

使いやすさの比較

1. 直感性と可読性

  • f-string変数や式がそのまま書ける ため、コードの可読性が高いです。
  • format()柔軟性はあるが、記述が冗長になりやすい
  • %シンプルだが、読みづらくバグの温床にもなりやすい

2. 複雑な構造に対応できるか

たとえば辞書や計算式を埋め込みたい場合:

user = {"name": "Alice", "age": 30}
print(f"My name is {user['name']} and I will be {user['age'] + 1} next year.")

このような 式埋め込みができるのはf-stringだけの特権です。

パフォーマンス比較

Python の timeit モジュールで実行速度を比較してみましょう。

1. ベンチマークコード

import timeit

name = "Alice"
age = 30

print("f-string:", timeit.timeit("f'My name is {name} and I am {age}.'", globals=globals()))
print("format():", timeit.timeit("'My name is {} and I am {}.'.format(name, age)", globals=globals()))
print("% operator:", timeit.timeit("'My name is %s and I am %d.' % (name, age)", globals=globals()))

2. 実行結果(例)

方法 実行時間(秒、10万回実行)
f-string 0.12
format() 0.19
% 演算子 0.17

3. 考察

  • f-string が最速
  • format() は一番遅い
  • % は中間程度

Python公式ドキュメントでも、f-string はパフォーマンス的にも推奨されています。

実用面での使い分け

1. Python バージョンによる制限

  • Python 3.5 以下:f-string 非対応 → format() を使う
  • Python 3.6 以上:f-string を推奨

2. チームやプロジェクトのルールに注意

  • 混在するとレビューや保守が難しくなる
  • チームで 書式統一のコーディング規約を決めておくのがベスト
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?