範本方法

Python 中的正規表示法

Maria Eugenia Inzaugarat

Data Scientist

Template 字串

  • 語法更簡單
  • 比 f-strings 慢
  • 受限:不支援格式規格
  • 適合處理外部已格式化的字串
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-strings。
    • 相容所有 Python 版本。
  • f-strings

    • 通常最建議使用的方法。
    • 僅適用於較新的 Python 版本(3.6+)。
  • Template 字串

    • 處理外部或使用者提供的字串時使用
Python 中的正規表示法

一起來練習吧!

Python 中的正規表示法

Preparing Video For Download...