Template
Python の version 2.4 から Template という仕組みが追加されている(stringモジュール内)。
Template とは以前からある %*1 による置き換えではなく、
辞書型(dict)のキー、もしくは辞書に類似した仕組みを要素として使った置き換えをする仕組みである。
substitute と safe_substitute
Template クラスでは substitute と safe_substitute という2つのメソッドを持つ。
Template_Instance.substitute( dictionary )
Template_Instance.safe_substitute( dictionary )
2つのメソッドの違いはプレースホルダを置き換えられなかった場合の動作の違いです。
- substitute の場合、ValueError の例外を raise します。
- safe_substitute の場合、プレースホルダ名がそのまま使用します。
サンプルコード
#!/usr/bin/env python # coding: utf-8 import string; tmp = string.Template( "I'm ${name}. I'm from ${country}." ); print tmp.substitute( { 'name': 'NelNal', 'country': 'Tokyo' } ); print tmp.substitute( { 'name': 'Chan', 'country': 'China' } ); print tmp.substitute( name='Tom', country='America' );