Pythonのテンプレート文字列クラスは、テンプレートフィールドをユーザが提供する適切な置換文字列に置き換える、単純な文字列置換の方法を提供します。
時には、置換のために他のフォーマット文字列を使うよりも、より簡単に置換できる文字列を持つことが好ましい場合があります。
テンプレート文字列はまさにこの目的のために使われ、最小限の手間で例外なく簡単に文字列を置き換えることができます。
文字列テンプレートルール
テンプレート文字列は $ による置換をサポートしており、以下のルールに従います。
-
$$-> これは、単一の$シンボルに対するエスケープシーケンスです。 -
$identifier-> これは置換語のプレースホルダーです。 -
${identifier}->$identifierと同じ意味です。プレースホルダーの後に有効な文字が現れるが、プレースホルダーの一部ではない場合に使用されます。 - それ以外の
$はValueError例外を発生させます。
以下は、基本的なテンプレート置換を示す例です。
from string import Template
# Create a template with 'name' as the placeholdertemplate = Template('Hello $name!')
student = 'Amit'
# Perform the template substitution and print the resultprint(template.substitute(name=student))
|
結果は以下の通りです。
Hello Amit! |
以下は、テンプレート代入の他のルールを説明するための例です。
from string import Template
# Create a template with $CODE as the placeholder# The $$ is to escape the dollar signtemplate = Template('The generated Code is ${CODE}-$$100')
code = 'H875'
# Perform the template substitution and print the resultprint(template.substitute(CODE=code))
|
結果は以下の通りです。
The generated Code is H875-$100 |
String Template クラスのメソッド
1. テンプレート コンストラクタ
先ほどのスニッパーで、Template(template_string) を使って文字列テンプレートオブジェクトを作成したところで、すでにこのことに気づきました。
フォーマット テンプレートオブジェクト = テンプレート(template_string)` とします。
2. substitute(mapping, **kwargs)
これも先ほどのスニペットの一部で、mappingからキーワード引数 kwargs にテンプレート代入を行います。
キーワード引数は置換のプレースホルダーとして渡すので、第2引数は **kwargs になります。
したがって、テンプレート代入のための辞書として渡される。
この点を説明するために、テンプレートの文字列に辞書を渡す方法を示します。
from string import Template
template = Template('The shares of $company have $state. This is $reaction.')
# Perform the template substitution and print the resultprint(template.substitute(state = 'dropped', company='Google', reaction='bad'))
# Perform substitution by passing a Dictionarydct = {'state': 'risen', 'company': 'Apple', 'reaction': 'good'}
print(template.substitute(**dct))
# Incomplete substitution results in a KeyErrortry:
template.substitute(state = 'dropped')
except KeyError:
print('Incomplete substitution resulted in KeyError!')
|
結果は以下の通りです。
The shares of Google have dropped. This is bad.
The shares of Apple have risen. This is good.
Incomplete substitution resulted in KeyError!
|
3. safeanthus_substitute(mapping, **kwargs)
これは substitute() と似ているが、mapping と kwargs にプレースホルダーがない場合、 KeyError 例外が発生する代わりに、元のプレースホルダーがそのまま結果の文字列に表示される点が異なる。
from string import Template
template = Template('The shares of $company have $state. This is $reaction.')
print(template.safe_substitute(company='Google'))
|
結果は以下の通りです。
The shares of Google have $state. This is $reaction. |
見ての通り、KeyErrorは発生せず、不完全ではありますが、エラーのない置換が行われます。
これが置換が「安全」である理由です。
Template Class の属性
Template オブジェクトは template 属性を持っており、これはテンプレートの文字列を返します。
この属性は変更することができますが、この属性の値を変更しないのがよい習慣です。
from string import Template
t = Template('Hello $name, are you $cond?')
print(t.template)
|
結果は以下の通りです。
Hello $name, are you $cond? |
まとめ
この記事では、文字列テンプレートクラスと、テンプレート文字列の規則的で安全な置換のためのメソッドのいくつかについて学びました。
また、シンプルで簡単な文字列置換のためにそれらをどのように使用するかも見てきました。
この記事もチェック:Pythonのreplaceメソッドを使って文字列を置換する方法
参考文献
- Python Template Strings
- テンプレート文字列に関するJournalDevの記事