🔧 阿川の電商水電行
Shopify 顧問、維護與客製化
💡
小任務 / 單次支援方案
單次處理 Shopify 修正/微調
⭐️
維護方案
每月 Shopify 技術支援 + 小修改 + 諮詢
🚀
專案建置
Shopify 功能導入、培訓 + 分階段交付

引言

我平常寫 Ruby,偶爾會因為興趣寫寫 Python。這次,發現不知道什麼時候被新增了一個叫 t-strings 的不熟悉功能,於是我查了一查。

在 Python 3.14 中引入的 t-strings

2025/10/07 (週二) (當地時間) Python 3.14 正式釋出 🚀

根據釋出內容,似乎新增了 t-strings (PEP 750: 模板字串) 這個功能。

模板字串是一種用於自定義字串處理的新機制。它們共享 f-strings 的熟悉語法,但與 f-strings 不同的是,返回的是表示字串的靜態和插值部分的物件,而不是簡單的 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,而是保持模板結構進行後續處理」的機制。換句話說,想要使用 t-strings 而非 f-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,靜態部分(字面)則直接連結。

    參數:
        template (Template):
            從 t-strings 獲得的 Template 物件。
        processor (Callable[[str], str], 可選):
            在最終將 Template 物件的插值埋入字串之前只應用一次的函數。
            默認情況下,該函數返回輸入的恒等函數。

    返回:
        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=%E6%B3%95%E4%BC%8A%E5%8D%9A%20%E8%97%8D%E8%89%B2%E5%A1%97%E6%96%99'

總結

t-strings 的出現使得 Python 的字串處理變得更加靈活。

  • 如果立即想要 str,則使用 f-strings
  • 如果希望進行後續的自定義處理(如轉義等),則使用 t-strings

這樣根據不同場景適當選擇使用會比較好。

版本信息

$ uv run python --version
Python 3.14.0

參考資料

過去撰寫的相關文章


原文出處:https://qiita.com/QUANON/items/ad474a884b3259315a29


精選技術文章翻譯,幫助開發者持續吸收新知。

共有 0 則留言


精選技術文章翻譯,幫助開發者持續吸收新知。
🏆 本月排行榜
🥇
站長阿川
📝22   💬9   ❤️5
639
🥈
我愛JS
📝4   💬13   ❤️7
263
🥉
御魂
💬1  
3
#4
2
#5
1
評分標準:發文×10 + 留言×3 + 獲讚×5 + 點讚×1 + 瀏覽數÷10
本數據每小時更新一次
🔧 阿川の電商水電行
Shopify 顧問、維護與客製化
💡
小任務 / 單次支援方案
單次處理 Shopify 修正/微調
⭐️
維護方案
每月 Shopify 技術支援 + 小修改 + 諮詢
🚀
專案建置
Shopify 功能導入、培訓 + 分階段交付