使用Template格式化Python字符串


對Python字符串,除了比較老舊的%,以及用來替換掉%的format,及在python 3.6中加入的f這三種格式化方法以外,還有可以使用Template對象來進行格式化。

 

from string import Template,可以導入Template類。

實例化Template類需要傳入一個Template模板字符串。

class Template(metaclass=_TemplateMetaclass):
    """A string class for supporting $-substitutions."""

    delimiter = '$'
    idpattern = r'[_a-z][_a-z0-9]*'
    flags = _re.IGNORECASE

    def __init__(self, template):
        self.template = template

 

字符串默認以%作為定界符

# 默認的定界符是$,即會將$之后內容匹配的字符串進行替換
s = Template('hello, $world!')
print(s.substitute(world='python'))
# hello, python!

實例化Template之后,返回對象s,調用對象s的substitute,傳入替換的數據,最終返回替換之后的結果。

 

如果需要對定界符進行修改,可以創建一個Template的子類,在子類中覆蓋掉Template的類屬性delimiter,賦值為需要重新設定的定界符。

# 可以通過繼承Template類的方式進行替換
class CustomerTemplate(Template):
    delimiter = '*'

t = CustomerTemplate('hello, *world!')
print(t.substitute(world='python'))
# hello, python!

上面的例子中,輸出和未修改定界符之前是一樣的,都是hello, python!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM