テンプレート(Template関数)

投稿者: | 2022-10-21
  • fromatメソッドやf-stingを使ってもできるが、Template関数を使った方法は、元となる文字列を読み込み専用にできるというメリットがある
  • 変数sに別の文字列を代入してしまうことを防止できるし、ほかの人が作成した文章を利用する場合など
import string

s = """\
Hi $name
$contents
Have a good day!
"""

t = string.Template(s)
contents = t.substitute(name='Bob', contents='How are you?')
print(contents)
  • フォーマットのテキストをあるとする、それをopenで開き、readで読み込んだTemplateの引数に渡し、substituteで操作するとテキストファイルの内容をテンプレートとした文章が作成できる
$name さん

おつかれさまです、$mynameです。

$contents

以上、よろしくおねがいします。

$myname
temp = r'/Users/mbp441/Desktop/mail_template.txt'

import string

with open(temp) as f:
    t = string.Template(f.read())
    
contents = t.substitute(name="山田", myname="田中", contents="了解しました。")
print(contents)