string.templatelib -- テンプレート文字列サポート
このモジュールは PEP 750 で定義されているテンプレート文字列(t-strings)をサポートします。テンプレート文字列は t プレフィックスを使って作成され、結合される前のリテラル文字列部分と補間値の両方にアクセスできます。
対応ポート: テンプレート文字列はコンパイル時に MICROPY_PY_TSTRINGS を有効にする必要があります。デフォルトでは alif, mimxrt, samd (SAMD51 のみ)ポート、unix (ライク)版、webassembly ベース pyscript 版を含み、フル機能レベルで有効になっています。
クラス
- class string.templatelib.Template(*args)
テンプレート文字列を表します。テンプレートオブジェクトは通常 t-string 構文(
t"...")で作成されますが、コンストラクタを使って直接構築することもできます。- strings
補間処理の間に現れる文字列リテラルのタプル。
- interpolations
補間された式を表す
Interpolationオブジェクトのタプル。
- values
テンプレート内の各補間から
value属性を含むタプルを返す読取り専用プロパティ。
- __iter__()
テンプレートの内容を反復処理し、 出現順に文字列部分と
Interpolationオブジェクトを生成します。空文字列は省略されます。
- class string.templatelib.Interpolation(value, expression='', conversion=None, format_spec='')
テンプレート文字列内の補間式を表します。すべての引数はキーワード引数として渡せます。
- value
補間された式の評価値。
- expression
テンプレート文字列に現れた式の文字列表現。
- conversion
変換指定子(
's'または'r')が存在する場合はそれを返し、存在しない場合はNoneを返します。MicroPython は'a'変換をサポートしていないことに注意してください。
- format_spec
フォーマット指定文字列が存在する場合はそれを返し、存在しない場合は空の文字列を返します。
テンプレート文字列構文
テンプレート文字列は f-strings と同じ構文を使いますが、プレフィックスとして付くのは t となります。
name = "World"
template = t"Hello {name}!"
# テンプレートコンポーネントのアクセス
print(template.strings) # ('Hello ', '!')
print(template.values) # ('World',)
print(template.interpolations[0].expression) # 'name'
変換指定子
テンプレート文字列は、変換指定子をメタデータとして格納します。f-strings とは異なり、変換は自動的に適用されません。
value = "test"
t = t"{value!r}"
# t.interpolations[0].value == "test" (not repr(value))
# t.interpolations[0].conversion == "r"
処理コードは、必要に応じて明示的に変換を適用する必要があります。
フォーマット指定子
フォーマット指定は Interpolation のメタデータとして保存されます。f-strings とは異なり、フォーマットは自動的に適用されません。
pi = 3.14159
t = t"{pi:.2f}"
# t.interpolations[0].value == 3.14159 (not formatted)
# t.interpolations[0].format_spec == ".2f"
PEP 750 の規定に従い、f-strings とは異なり、テンプレート文字列は変換や書式指定を自動的に適用しません。これは、処理コードがこれらの処理方法を制御できるようにするための設計です。処理コードはこれらの属性を明示的に処理する必要があります。
デバッグフォーマット
デバッグフォーマット {expr=} がサポートされています。
x = 42
t = t"{x=}"
# t.strings == ("x=", "")
# t.interpolations[0].expression == "x"
# t.interpolations[0].conversion == "r"
重要
PEP 750 の規定に従い、f-strings とは異なり、テンプレート文字列は変換や書式指定を自動的に適用しません。これは、処理コードがこれらの処理方法を制御できるようにするための設計です。処理コードはこれらの属性を明示的に処理する必要があります。
MicroPython には format() 組み込み関数がありません。
使用例
フォーマットサポートなしの基本処理:
def simple_process(template):
"""単純なテンプレート処理"""
parts = []
for item in template:
if isinstance(item, str):
parts.append(item)
else:
parts.append(str(item.value))
return "".join(parts)
フォーマットサポート付きテンプレート処理:
from string.templatelib import Template, Interpolation
def convert(value, conversion):
"""value に変換指定子を適用"""
if conversion == "r":
return repr(value)
elif conversion == "s":
return str(value)
return value
def process_template(template):
"""変換とフォーマットサポートでテンプレートを処理"""
result = []
for part in template:
if isinstance(part, str):
result.append(part)
else: # Interpolation
value = convert(part.value, part.conversion)
if part.format_spec:
# str.format を使ってフォーマット指定子を適用
value = ("{:" + part.format_spec + "}").format(value)
else:
value = str(value)
result.append(value)
return "".join(result)
pi = 3.14159
name = "Alice"
t = t"{name!r}: {pi:.2f}"
print(process_template(t))
# 出力: "'Alice': 3.14"
# 他のフォーマット指定子も処理
value = 42
print(process_template(t"{value:>10}")) # " 42"
print(process_template(t"{value:04d}")) # "0042"
HTML エスケープの例:
def html_escape(value):
"""HTML 特殊文字のエスケープ"""
if not isinstance(value, str):
value = str(value)
return value.replace("&", "&").replace("<", "<").replace(">", ">")
def safe_html(template):
"""テンプレートを HTML-safe 文字列に変換"""
result = []
for part in template:
if isinstance(part, str):
result.append(part)
else:
result.append(html_escape(part.value))
return "".join(result)
user_input = "<script>alert('xss')</script>"
t = t"User said: {user_input}"
print(safe_html(t))
# 出力: "User said: <script>alert('xss')</script>"
関連項目
PEP 750 - テンプレート文字列仕様
Format String Syntax - フォーマット文字列構文
フォーマット文字列リテラル - Python の f-strings