2
2

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文字列の内部構造とパフォーマンス的利点

Posted at

概要

Python 3.6以降に導入された f文字列(formatted string literals) は、
可読性とパフォーマンスの両立を実現する構文的進化である。

% 演算子や str.format() に代わる新世代の文字列フォーマットとして、
どのようなメリット・内部構造・ベストプラクティスがあるのかを整理する。


1. 基本構文

name = "Alice"
age = 30
print(f"{name} is {age} years old.")
# 出力: Alice is 30 years old.
  • f"..." の中に {} で式を埋め込む
  • 任意の式が書ける(関数呼び出しも可)
print(f"{name.upper()} - {age + 1}")

2. 他のフォーマット方法との比較

# 旧形式(%演算子)
"%s is %d years old." % (name, age)

# formatメソッド
"{} is {} years old.".format(name, age)

# f文字列
f"{name} is {age} years old."

✅ 可読性:f文字列が最も直感的

✅ 型の自動変換:int, float, boolもそのまま埋め込める


3. パフォーマンス比較(簡易ベンチマーク)

import timeit

name = "Alice"
age = 30

print(timeit.timeit(lambda: f"{name} is {age}", number=1000000))      # 最速
print(timeit.timeit(lambda: "{} is {}".format(name, age), number=1000000))
print(timeit.timeit(lambda: "%s is %s" % (name, age), number=1000000))

⏱ 結果例(環境による差あり)

方式 実行時間(短いほど高速)
f文字列 ✅ 最速
str.format() 中程度
%演算子 遅め

4. フォーマット指定(浮動小数点など)

price = 1234.56789
print(f"Price: {price:.2f}")  # → Price: 1234.57
  • .2f → 小数点以下2桁表示
  • その他も {value:>10}(右寄せ), {value:0>5}(ゼロパディング)などが使用可能

5. デバッグ用途:=

Python 3.8以降、f文字列に = を使うと**「変数名=値」の出力**が可能:

user = "bob"
print(f"{user=}")  # 出力: user='bob'

→ ロギングやデバッグの効率が劇的に上がる


6. 注意点とベストプラクティス

❌ 多数の変数をネストした状態で書くと可読性が下がる

print(f"Result: {get_user(id).get('name', 'N/A').title()}")

→ ✅ 事前に変数化した方が安全・可読性向上


❌ セキュリティに注意(evalに近い側面)

danger = "{__import__('os').system('rm -rf /')}"

f"" では実行されないが、eval(f"...") のような使い方は絶対に避ける


結語

f文字列は、Pythonにおける文字列整形の最適解として設計された構文である。

  • 速度・可読性・拡張性の三拍子が揃い
  • デバッグ用途やログ出力にも応用可能
  • 既存の %format() からの移行も容易

Pythonicとは、“意図が読み取れる構文”であり、
f文字列はその設計哲学を最も明快に体現する記法のひとつである。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?