使用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,傳入替換的數據,最終返回替換之后的結果。
如果需要對定界符進行修改,可以創(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字符串的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python Pandas數據分析之iloc和loc的用法詳解
Pandas 是一個開放源碼、BSD 許可的庫,提供高性能、易于使用的數據結構和數據分析工具,它是一個強大的分析結構化數據的工具集,基礎是 Numpy2021-11-11