string.templatelib --- 樣板字串支援

本模組為 PEP 750 所定義的樣板字串(t-strings)提供支援。樣板字串使用 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 物件出現的順序逐一產出。空字串會被略過。

__add__(other: Template) Template

串接兩個樣板。回傳一個新的 Template,結合來自兩個樣板的字串與內插。

引發:

TypeError -- 若 other 不是 Template

禁止將樣板與 str 串接,以避免對於該字串應被視為字面值還是內插產生歧義:

t1 = t"Hello "
t2 = t"World"
result = t1 + t2  # Valid

# TypeError: cannot concatenate str to Template
result = t1 + "World"
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("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")

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: &lt;script&gt;alert('xss')&lt;/script&gt;"

另請參閱