string.templatelib --- テンプレート文字列のサポート¶
このモジュールは、PEP 750 で定義されているテンプレート文字列(t-string)のサポートを提供します。テンプレート文字列は t 接頭辞を使用して作成され、結合される前の文字列リテラル部分と補間された値の両方へのアクセスを提供します。
利用可否: テンプレート文字列は STM32 ベースの OpenMV Cam では サポートされていません。Alif ベースおよび i.MX RT ベースの OpenMV Cam でのみ利用できます。
クラス¶
- class string.templatelib.Template(*args)¶
テンプレート文字列を表します。Template オブジェクトは通常 t-string 構文(
t"...")によって作成されますが、コンストラクタを使用して直接構築することもできます。- strings¶
補間の間に現れる文字列リテラルのタプル。
- interpolations¶
補間された式を表す
Interpolationオブジェクトのタプル。
- values¶
テンプレート内の各補間の
value属性を含むタプルを返す読み取り専用プロパティ。
- __iter__() Iterator¶
テンプレートの内容を反復処理し、文字列部分と
Interpolationオブジェクトを出現順に生成します。空の文字列は省略されます。
- class string.templatelib.Interpolation(value: Any, expression: str = '', conversion: str | None = None, format_spec: str = '')¶
テンプレート文字列内の補間された式を表します。すべての引数はキーワード引数として渡すことができます。
- value¶
補間された式の評価された値。
- expression¶
テンプレート文字列内に現れたとおりの式の文字列表現。
- conversion¶
変換指定子(
's'または'r')が存在する場合はそれ、存在しない場合はNone。MicroPython は'a'変換をサポートしていない点に注意してください。
- format_spec¶
書式指定文字列が存在する場合はそれ、存在しない場合は空文字列。
テンプレート文字列の構文¶
テンプレート文字列は f-string と同じ構文を使用しますが、t 接頭辞を付けます:
name = "World"
template = t"Hello {name}!"
# Access template components
print(template.strings) # ('Hello ', '!')
print(template.values) # ('World',)
print(template.interpolations[0].expression) # 'name'
変換指定子¶
テンプレート文字列は変換指定子をメタデータとして格納します。f-string とは異なり、変換は自動的には適用されません:
value = "test"
t = t"{value!r}"
# t.interpolations[0].value == "test" (not repr(value))
# t.interpolations[0].conversion == "r"
処理コードは、必要に応じて変換を明示的に適用しなければなりません。
書式指定¶
書式指定は Interpolation オブジェクトにメタデータとして格納されます。f-string とは異なり、書式設定は自動的には適用されません:
pi = 3.14159
t = t"{pi:.2f}"
# t.interpolations[0].value == 3.14159 (not formatted)
# t.interpolations[0].format_spec == ".2f"
PEP 750 によれば、処理コードは書式指定を使用する必要はありませんが、存在する場合は尊重し、可能な限り f-string の動作に一致させるべきです。
デバッグ書式¶
デバッグ書式 {expr=} がサポートされています:
x = 42
t = t"{x=}"
# t.strings == ("x=", "")
# t.interpolations[0].expression == "x"
# t.interpolations[0].conversion == "r"
重要
PEP 750 に従い、f-string とは異なり、テンプレート文字列は変換や書式指定を自動的に適用しません。これは、処理コードがこれらの扱い方を制御できるようにするための設計です。処理コードはこれらの属性を明示的に処理しなければなりません。
MicroPython は組み込み関数 format() を提供していません。代わりに str.format() のような文字列書式設定メソッドを使用してください。
使用例¶
書式サポートなしの基本的な処理:
def simple_process(template):
"""Simple template processing"""
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):
"""Apply conversion specifier to value"""
if conversion == "r":
return repr(value)
elif conversion == "s":
return str(value)
return value
def process_template(template):
"""Process template with conversion and format support"""
result = []
for part in template:
if isinstance(part, str):
result.append(part)
else: # Interpolation
value = convert(part.value, part.conversion)
if part.format_spec:
# Apply format specification using 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))
# Output: "'Alice': 3.14"
# Other format specifications work too
value = 42
print(process_template(t"{value:>10}")) # " 42"
print(process_template(t"{value:04d}")) # "0042"
HTML エスケープの例:
def html_escape(value):
"""Escape HTML special characters"""
if not isinstance(value, str):
value = str(value)
return value.replace("&", "&").replace("<", "<").replace(">", ">")
def safe_html(template):
"""Convert template to HTML-safe string"""
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))
# Output: "User said: <script>alert('xss')</script>"
関連項目¶
PEP 750 - テンプレート文字列の仕様
Format string syntax - 書式文字列の構文
書式付き文字列リテラル - Python の f-string