Template 方法

Python 中的正则表达式

Maria Eugenia Inzaugarat

Data Scientist

Template 字符串

  • 语法更简单
  • 比 f-string 慢
  • 受限:不支持格式说明符
  • 适合处理外部格式化的字符串
Python 中的正则表达式

基础语法

from string import Template

my_string = Template('Data science has been called $identifier')
my_string.substitute(identifier="sexiest job of the 21st century")
'Data science has been called sexiest job of the 21st century'
Python 中的正则表达式

替换

  • 可使用多个 $identifier
  • 可使用变量
from string import Template
job = "Data science"
name = "sexiest job of the 21st century"

my_string = Template('$title has been called $description')
my_string.substitute(title=job, description=name)
'Data science has been called sexiest job of the 21st century'
Python 中的正则表达式

替换

  • 当标识符后跟有效字符时,用 ${identifier}

 

my_string = Template('I find Python very ${noun}ing but my sister has lost $noun')

my_string.substitute(noun="interest")
'I find Python very interesting but my sister has lost interest'
Python 中的正则表达式

替换

  • 使用 $$ 转义美元符号

 

my_string = Template('I paid for the Python course only $$ $price, amazing!')

my_string.substitute(price="12.50")
'I paid for the Python course only $ 12.50, amazing!'
Python 中的正则表达式

替换

  • 缺少占位符时抛出错误
favorite = dict(flavor="chocolate")

my_string = Template('I love $flavor $cake very much')
my_string.substitute(favorite)
Traceback (most recent call last):
KeyError: 'cake'
Python 中的正则表达式

替换

favorite = dict(flavor="chocolate")
my_string = Template('I love $flavor $cake very much')
try:
    my_string.substitute(favorite) 
except KeyError:
      print("missing information")
missing information
Python 中的正则表达式

安全替换

  • 始终尝试返回可用字符串
  • 缺失占位符会原样出现在结果中
favorite = dict(flavor="chocolate")
my_string = Template('I love $flavor $cake very much')

my_string.safe_substitute(favorite)
'I love chocolate $cake very much'
Python 中的正则表达式

应使用哪种?

  • str.format()

    • 适合入门。概念适用于 f-string。
    • 兼容所有 Python 版本。
  • f-strings

    • 通常优先于其他方法。
    • 仅适用于现代 Python 版本(3.6+)。
  • Template 字符串

    • 适用于外部或用户提供的字符串
Python 中的正则表达式

¡Vamos a practicar!

Python 中的正则表达式

Preparing Video For Download...