關於string.Template的簡單介紹

1、簡介

  string模塊定義了一種新字符串類型Template,它簡化了特定的字符串置換操做。正則表達式

  何謂「簡化」?咱們能夠先想一下咱們以前比較經常使用的有關字符串的「置換」操做有哪些:一種是利用%操做符實現,另一種是格式化字符串format實現。那麼,相比於這兩種方法,string.Template究竟簡化在何處呢?ide

  那咱們就如下面的代碼爲例簡單說明一下string.Template的用法與上述兩種方式的區別:spa

# -*- coding: utf-8  -*-
# -*- Author: WangHW -*-
import string

values = {'var':3.3333333}
#1
t1 = string.Template("""
Variable        : $var
Escape          : $$
Variable in text: ${var}iable
""")
print('TEMPLATE:',t1.substitute(values))
print('############################')
#2
s = """
Variable        : %(var)s
Escape          : %%
Variable in text: %(var)siable
"""
print('INTERPOLATION:',s % values)
print('############################')

#3
s1 = """
Variable         {var}
Escape          : {{}}
Variable in text: {var}iable
"""
print('FORMAT:',s1.format(**values))

結果以下:code

  上面的代碼分別利用string.Template方法、%操做符以及format方法進行了字符串的置換操做。這裏咱們能夠看出string.Template是利用$符號進行「關聯」,用substitute方法取值的orm

  這裏直接給出結論:利用string.Template方法是不須要考慮參數的數據類型的!這是string.Template方法與後面兩種方法最重要的不一樣之處。string.Template方法直接將參數轉換爲字符串格式,而後將轉換後的字符串直接插入結果中去。沒有可用的格式化選項供咱們選擇,例如,對於一個浮點數(如上述例子所示)來說,咱們沒辦法控制表明這個浮點數數值的位數。對象

2、safe_substitute方法

  上例中咱們利用substitute取值。你們確定會問了:若是$關聯的字符串在前面定義的values中不存在怎麼辦?難道會報錯嗎?
blog

  答案是確定的!爲了不上述問題的產生咱們利用safe_substitute方法取值,固然能夠跟原生的substitute方法對比一下:繼承

# -*- coding: utf-8  -*-
# -*- Author: WangHW -*-
import string

values = {'var':'foo'}

t = string.Template('$var is here but $missing is not provided')

try:
    print('substitute()     :',t.substitute(values))
except KeyError as err:
    print('ERROR:',str(err))

print('safe_substitute():',t.safe_substitute(values))

  結果以下:utf-8

  你們能夠看到:values中並無表明key的字符串'missing',而咱們在Template中卻試圖利用$missing取其對應的值。所以substitute方法會報錯,而safe_substitute方法能夠巧妙的「避免」這個錯誤,保證程序的流暢性。字符串

3、進階:模塊功能的「修改」

  在實際中,你們可能習慣利用%操做符去進行字符串的置換了,那麼,若是咱們既想利用string.Template方法的便捷性,又想按照本身的意願與需求定義額外的功能,這就須要咱們新定義一個繼承自string.Template的類(例如命名爲MyTempate),在這裏修改其中的某些屬性去知足咱們的需求。

  下面代碼中MyTemplate類繼承自string.Template,修改了操做符delimiter與id模式idpattern,實現了利用%關聯表明key的字符串,而後利用正則表達式使safe_substitute()只能匹配出帶下劃線的且由a-z組成的字符串:

# -*- coding: utf-8  -*-
# -*- Author: WangHW -*-
import string

class MyTemplate(string.Template):
    #操做符
    delimiter = '%'
    #id模式
    idpattern = '[a-z]+_[a-z]+'


if __name__ == '__main__':
    template_text = '''
    Delimiter : %%
    Replaced  : %with_underscore
    Ignored   : %notunderscored
    '''
    d = {
        'with_underscore':'replaced',
        'notunderscored':'not replaced'
    }

    t = MyTemplate(template_text)
    print('Modified ID pattern:')
    print(t.safe_substitute(d))

  結果以下:

  上例中,因爲表明key的字符串‘notunderscored’沒有下劃線,沒有匹配到,因此結果中只能得出%notunderscored,不能取到具體的值。

  須要注意的是:這種方法在實際中很是經常使用!在實際中咱們須要根據具體的需求靈活的「更改」模塊中某個對象的某個屬性去實現具體的需求!

相關文章
相關標籤/搜索