python的Template
Template無疑是一個好東西,可以將字符串的格式固定下來,重復利用。同時Template也可以讓開發人員可以分別考慮字符串的格式和其內容了,無形中減輕了開發人員的壓力。
Template屬于string中的一個類,所以要使用的話可以用以下方式調用
from string import Template
Template有個特殊標示符$,它具有以下的規則:
-
它的主要實現方式為$xxx,其中xxx是滿足python命名規則的字符串,即不能以數字開頭,不能為關鍵字等
-
如果$xxx需要和其他字符串接觸時,可用{}將xxx包裹起來(以前似乎使用'()',我的一本參考書上是這樣寫的,但是現在的版本應該只能使用'{}')。例如,aaa${xxx}aaa
Template中有兩個重要的方法:substitute和safe_substitute.
這兩個方法都可以通過獲取參數返回字符串
>>s=Template(There $a and $b) >>print s.subtitute(a='apple',b='banana') There apple and banana >>print s.safe_substitute(a='apple',b='banbana') There apple and banbana
還可以通過獲取字典直接傳遞數據,像這樣
>>s=Template(There $a and $b) >>d={'a':'apple','b':'banbana'} >>print s.substitute(d) There apple and banbana
它們之間的差別在于對于參數缺少時的處理方式。
Template的實現方式是首先通過Template初始化一個字符串。這些字符串中包含了一個個key。通過調用substitute或safe_subsititute,將key值與方法中傳遞過來的參數對應上,從而實現在指定的位置導入字符串。這個方式的一個好處是不用像print ‘%s’之類的方式,各個參數的順序必須固定,只要key是正確的,值就能正確插入。通過這種方式,在插入很多數據的時候就可以松口氣了。可是即使有這樣偷懶的方法,依舊不能保證不出錯,如果key少輸入了一個怎么辦呢?
substitute是一個嚴肅的方法,如果有key沒有輸入,那就一定會報錯。雖然會很難看,但是可以發現問題。
safe_substitute則不會報錯,而是將$xxx直接輸入到結果字符串中,如
there apple and $b
這樣的好處是程序總是對的,不用被一個個錯誤搞得焦頭爛額。
Template可以被繼承,它的子類可以進行一些‘個性化’操作...
通過修改delimiter字段可以將$字符改變為其他字符,如“#”,不過新的標示符需要符合正則表達式的規范。
通過修改idpattern可以修改key的命名規則,比如說規定第一個字符開頭必須是a,這對規范命名倒是很有好處。當然,這也是通過正則表示實現的。
from string import Template class MyTemplate(Template): delimiter = "#" idpattern = "[a][_a-z0-9]*" def test(): s='#aa is not #ab' t=MyTemplate(s) d={'aa':'apple','ab':'banbana'} print t.substitute(d) if __name__=='__main__': test()
參考資料:https://docs.python.org/2/library/string.html#template-strings
來自:http://my.oschina.net/u/241670/blog/309856