string.templatelib --- รองรับ Template String

โมดูลนี้รองรับ template string (t-string) ตามที่กำหนดใน PEP 750 Template string สร้างขึ้นโดยใช้คำนำหน้า t และให้การเข้าถึงทั้งส่วนสตริงตัวอักษรและค่าที่แทรกก่อนที่จะนำมารวมกัน

ความพร้อมใช้งาน: Template string ไม่ รองรับบน OpenMV Cam ที่ใช้ STM32 มีให้ใช้เฉพาะบน OpenMV Cam ที่ใช้ Alif- และ i.MX RT-based เท่านั้น

คลาส

class string.templatelib.Template(*args)

แสดง template string ออบเจ็กต์ Template โดยปกติสร้างด้วยไวยากรณ์ t-string (t"..." ) แต่ก็สามารถสร้างโดยตรงโดยใช้ constructor ได้เช่นกัน

strings

ทูเพิลของสตริงตัวอักษรที่ปรากฏระหว่างการแทรกค่า

interpolations

ทูเพิลของออบเจ็กต์ Interpolation ที่แสดงนิพจน์ที่แทรก

values

คุณสมบัติแบบอ่านอย่างเดียวที่คืนค่าทูเพิลประกอบด้วยแอตทริบิวต์ value จากการแทรกแต่ละรายการใน template

__iter__() Iterator

วนซ้ำเนื้อหา template ส่งคืนส่วนสตริงและออบเจ็กต์ Interpolation ตามลำดับที่ปรากฏ สตริงว่างจะถูกละเว้น

__add__(other: Template) Template

เชื่อม template สองรายการเข้าด้วยกัน คืนค่า Template ใหม่ที่รวมสตริงและการแทรกจาก template ทั้งสอง

Raises:

TypeError -- ถ้า other ไม่ใช่ Template

การต่อ 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 = '')

แสดงนิพจน์ที่แทรกภายใน template string อาร์กิวเมนต์ทั้งหมดสามารถส่งเป็น keyword argument ได้

value

ค่าที่ประมวลผลแล้วของนิพจน์ที่แทรก

expression

การแสดงสตริงของนิพจน์ตามที่ปรากฏใน template string

conversion

ตัวระบุการแปลง ('s' หรือ 'r') ถ้ามี มิฉะนั้นเป็น None โปรดทราบว่า MicroPython ไม่รองรับการแปลง 'a'

format_spec

สตริงข้อกำหนดรูปแบบถ้ามี มิฉะนั้นเป็นสตริงว่าง

ไวยากรณ์ Template String

Template string ใช้ไวยากรณ์เดียวกับ 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'

ตัวระบุการแปลง

Template string จัดเก็บตัวระบุการแปลงเป็น metadata ต่างจาก f-string การแปลงจะไม่ถูกนำไปใช้โดยอัตโนมัติ:

value = "test"
t = t"{value!r}"
# t.interpolations[0].value == "test" (not repr(value))
# t.interpolations[0].conversion == "r"

โค้ดที่ประมวลผลต้องนำการแปลงไปใช้อย่างชัดเจนเมื่อจำเป็น

ข้อกำหนดรูปแบบ

ข้อกำหนดรูปแบบถูกจัดเก็บเป็น metadata ในออบเจ็กต์ 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 ให้มากที่สุดเท่าที่เป็นไปได้

รูปแบบ Debug

รูปแบบ debug {expr=} รองรับ:

x = 42
t = t"{x=}"
# t.strings == ("x=", "")
# t.interpolations[0].expression == "x"
# t.interpolations[0].conversion == "r"

สำคัญ

ตาม PEP 750 ต่างจาก f-string template string จะไม่นำการแปลงหรือข้อกำหนดรูปแบบไปใช้โดยอัตโนมัติ นี่คือการออกแบบโดยเจตนาเพื่อให้โค้ดที่ประมวลผลควบคุมวิธีจัดการ โค้ดที่ประมวลผลต้องจัดการแอตทริบิวต์เหล่านี้อย่างชัดเจน

MicroPython ไม่มีฟังก์ชัน built-in 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)

การประมวลผล template พร้อมรองรับรูปแบบ:

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"

ตัวอย่างการ escape 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;"

ดูเพิ่มเติม