はじめに
僕は普段 Ruby を書いており、趣味でたまに Python を嗜む程度のプログラマです。今回、知らない間に t-strings という聞き慣れない機能が追加されていたので調べてみました。
Python 3.14 で導入された t-strings
2025/10/07 (火) (現地時間) に Python 3.14 がリリースされました 🚀
リリースの内容を見ると t-strings (PEP 750: Template Strings) という機能が追加されたようです。
Template strings are a new mechanism for custom string processing. They share the familiar syntax of f-strings but, unlike f-strings, return an object representing the static and interpolated parts of the string, instead of a simple str.
これはなんでしょう? 既存の f-strings とは何が違うのでしょう? 🤔
f-strings と t-strings の違い
| 記法 | 振る舞い | |
|---|---|---|
| f-strings | f"..." |
文字列 (str) を生成する |
| t-strings | t"..." |
新しい型である Template (string.templatelib.Template)のオブジェクトを生成する |
name: str = 'ステルスレイダー'
diameter: float = 58.49
# f-strings は文字列 (str) を生成する。
f"僕の好きなヨーヨー「{name}」の幅は約 {diameter:.1f}mm です。"
# '僕の好きなヨーヨー「ステルスレイダー」の幅は約 58.5mm です。'
type(f"僕の好きなヨーヨー「{name}」の幅は約 {diameter:.1f}mm です。")
#<class 'str'>
# t-strings は Template オブジェクトを生成する。
t"僕の好きなヨーヨー「{name}」の幅は約 {diameter:.1f}mm です。"
# Template(strings=('僕の好きなヨーヨー「', '」の幅は約 ', 'mm です。'), interpolations=(Interpolation('ステルスレイダー', 'name', None, ''), Interpolation(58.55, 'diameter', None, '.1f')))
type(t"僕の好きなヨーヨー「{name}」の幅は約 {diameter:.1f}mm です。")
# <class 'string.templatelib.Template'>
この Template オブジェクトは以下の属性で構成されます。
| 属性 | 説明 |
|---|---|
| strings | テンプレート内の静的な文字列 (リテラル文字列) のタプル |
| interpolations | テンプレート内の動的な置換部分 (中括弧 {} 内の部分) を表現する Interpolation のタプル |
| values | テンプレート内のすべての置換された値のタプルです |
from string.templatelib import Template
name: str = 'ステルスレイダー'
diameter: float = 58.49
template: Template = t"僕の好きなヨーヨー「{name}」の幅は約 {diameter:.1f}mm です。"
template.strings
# ('僕の好きなヨーヨー「', '」の幅は約 ', 'mm です。')
template.interpolations
# (Interpolation('ステルスレイダー', 'name', None, ''), Interpolation(58.49, 'diameter', None, '.1f'))
template.values
# ('ステルスレイダー', 58.55)
t-strings の用途
t-strings は「いきなり str にせず、テンプレート構造のまま後続処理を実行する」ための仕組みです。つまり、f-strings ではなく t-strings を使いたいのは例えば以下のような場面です。
- 文字列を生成する前に、あるいは生成と同時に独自の処理 (エスケープ等) を必ず通したい
- 例
- HTML への安全な差し込み(エスケープ)を行う
- URL 文字列のクエリパラメータが URL エンコードされることを保証する
- SQL 文字列のプレースホルダにパラメータを埋め込む
- 例
以下は、Template オブジェクトに任意の前処理を差し込んでから文字列化する関数の例です。
from string.templatelib import Template
from collections.abc import Callable
import urllib.parse
def render_template(
template: Template, processor: Callable[[str], str] = lambda s: s
) -> str:
"""
Template を走査して文字列を生成する。
動的部分({...} の値)に processor を適用し、静的部分 (リテラル) はそのまま連結する。
Args:
template (Template):
t-strings から得られる Template オブジェクト。
processor (Callable[[str], str], optional):
Template オブジェクトの補間値を最終的に文字列へ埋め込む前に 1 度だけ適用する関数。
省略時は恒等関数 (入力をそのまま返す関数) として動作する。
Returns:
str: 静的部分と processor 適用後の補間値を結合した最終的な文字列。
"""
values: list[str] = []
for item in template:
if isinstance(item, str):
values.append(item)
else:
values.append(processor(str(item.value)))
return "".join(values)
# 例 1: 文字列を大文字にする処理を挟む。
keyword: str = "dv888"
template: Template = t"http://yoyonest.jp/view/search?search_keyword={keyword}"
render_template(template)
# 'http://yoyonest.jp/view/search?search_keyword=dv888'
render_template(template, lambda s: s.upper())
# 'http://yoyonest.jp/view/search?search_keyword=DV888'
# 例 2: 文字列を URL エンコードする処理を挟む。
keyword: str = "ファイホ セラコート グリーン"
template: Template = t"http://yoyonest.jp/view/search?search_keyword={keyword}"
render_template(template)
# 'http://yoyonest.jp/view/search?search_keyword=ファイホ セラコート グリーン'
render_template(template, urllib.parse.quote)
# 'http://yoyonest.jp/view/search?search_keyword=%E3%83%95%E3%82%A1%E3%82%A4%E3%83%9B%20%E3%82%BB%E3%83%A9%E3%82%B3%E3%83%BC%E3%83%88%20%E3%82%B0%E3%83%AA%E3%83%BC%E3%83%B3'
まとめ
t-strings の登場で、Python の文字列処理はより柔軟になりました。
- すぐに str がほしいなら f-strings
- 後続で独自の処理 (エスケープ等) を挟みたいなら t-strings
という感じで、場面に応じて使い分けるとよさそうです。
バージョン情報
$ uv run python --version
Python 3.14.0
参考
- Python Release Python 3.14.0 | Python.org
- What’s new in Python 3.14 — Python 3.14.0 documentation
- PEP 750 – Template Strings | peps.python.org
- string.templatelib — Support for template string literals — Python 3.14.0 documentation
- Python's new t-strings | Dave Peck
- Python 3.14: The NEW T-strings are Awesome - YouTube