专栏名称: Python开发者
人生苦短,我用 Python。伯乐在线旗下账号「Python开发者」分享 Python 相关的技术文章、工具资源、精选课程、热点资讯等。
今天看啥  ›  专栏  ›  Python开发者

Python 3.14 t-string 要来了,它与 f-string 有何不同?

Python开发者  · 公众号  · Python  · 2025-05-21 10:21
    

文章预览

Python 最近出了个大新闻:PEP-750 t-string 语法被正式采纳了! 这意味着 Python 将在今年 10 月发布的 3.14 版本中引入一种新的字符串前缀  t ,称为模板字符串(Template Strings),即 t-string。 这是继 f-string 之后,字符串处理能力的重大升级,旨在提供更安全、更灵活的字符串插值处理机制。 t-string 的基本语法与 f-string 非常相似,但得到的结果却大为不同: name =  "World" # f-string 语法 formatted =  f"Hello  {name} !" print(type(formatted))   # 输出: print(formatted)   # 输出:Hello World! # t-string 语法 templated = t "Hello {name}!" print(type(templated))   # 输出: print(templated.strings)   # 输出:('Hello ', '') print(templated.interpolations[ 0 ].value)   # 输出:World print( "" .join(         item  if  isinstance(item, str)  else  str(item.value)          for  item  in  templated     ))   # 输出:Hello World! 如上所述 ………………………………

原文地址:访问原文地址
快照地址: 访问文章快照
总结与预览地址:访问总结与预览