使用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
字符串默認以%作為定界符
# 默認的定界符是$,即會將$之后內(nèi)容匹配的字符串進行替換 s = Template('hello, $world!') print(s.substitute(world='python')) # hello, python!
實例化Template之后,返回對象s,調(diào)用對象s的substitute,傳入替換的數(shù)據(jù),最終返回替換之后的結(jié)果。
如果需要對定界符進行修改,可以創(chuàng)建一個Template的子類,在子類中覆蓋掉Template的類屬性delimiter,賦值為需要重新設定的定界符。
# 可以通過繼承Template類的方式進行替換 class CustomerTemplate(Template): delimiter = '*' t = CustomerTemplate('hello, *world!') print(t.substitute(world='python')) # hello, python!
上面的例子中,輸出和未修改定界符之前是一樣的,都是hello, python!
以上這篇使用Template格式化Python字符串的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python實現(xiàn)處理apiDoc轉(zhuǎn)swagger的方法詳解
這篇文章主要為大家詳細介紹了Python實現(xiàn)處理apiDoc轉(zhuǎn)swagger的方法,文中的示例代碼講解詳細,具有一定的學習價值,感興趣的小伙伴可以了解一下2023-02-02Python Pandas數(shù)據(jù)分析之iloc和loc的用法詳解
Pandas 是一個開放源碼、BSD 許可的庫,提供高性能、易于使用的數(shù)據(jù)結(jié)構(gòu)和數(shù)據(jù)分析工具,它是一個強大的分析結(jié)構(gòu)化數(shù)據(jù)的工具集,基礎是 Numpy2021-11-11Python3實現(xiàn)的Mysql數(shù)據(jù)庫操作封裝類
這篇文章主要介紹了Python3實現(xiàn)的Mysql數(shù)據(jù)庫操作封裝類,涉及Python針對mysql數(shù)據(jù)庫的連接、查詢、更新及關(guān)閉連接等相關(guān)操作技巧,需要的朋友可以參考下2018-06-06