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...