「Python入門」文字列を扱うstring.Templateの使い方

pythonコード
# -*- coding: utf-8 -*-
import string

t = string.Template('$var’)
print(t.pattern.pattern)

class DemoTemplate(string.Template):
delimiter = '{{'
pattern = r""’
\{\{(?:
(?P<escaped>\{\{) | # Escape sequence of two delimiters
(?P<named>[_a-z][_a-z0-9]*)\}\} | # delimiter and a Python identifier
{(?P<braced>[_a-z][_a-z0-9]*)}\}\} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
"’

t2 = DemoTemplate(""’
{{{{
{{var}}
"’)

print('MATCHES: ', t2.pattern.findall(t2.template))
print('SUBSTITUTED: ', t2.safe_substitute(var=’replacement’))

出力結果
\$(?:
(?P<escaped>\$) | # Escape sequence of two delimiters
(?P<named>[_a-z][_a-z0-9]*) | # delimiter and a Python identifier
{(?P<braced>[_a-z][_a-z0-9]*)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)

MATCHES: [('{{', ", ", "), (", 'var’, ", ")]
SUBSTITUTED:
{{
replacement

Python

Posted by arkgame