Python 中開發(fā)pattern的string模板(template) 實例詳解
更新時間:2017年04月01日 09:37:28 投稿:lqh
這篇文章主要介紹了Python 中開發(fā)pattern的string模板(template) 實例詳解的相關(guān)資料,需要的朋友可以參考下
定制pattern的string模板(template) 詳解
string.Template的pattern是一個正則表達式, 可以通過覆蓋pattern屬性, 定義新的正則表達式.
如: 使用新的定界符"{{", 把{{var}}作為變量語法.
代碼:
# -*- coding: utf-8 -*- ''''' Created on 2014.6.5 @author: Administrator @edition : python 3.3.0, eclipse pydev ''' import string t = string.Template('$var') print(t.pattern.pattern) class MyTemplate(string.Template): delimiter = '{{' pattern = r''''' \{\{(?: (?P<escaped>\{\{) | # Escape sequence of two delimiters (?P<named>[_a-z][_a-z0-9]*)\}\} | # delimiter and a Python identifier {(?P<braced>[_a-z][_a-z0-9]*)}\}\} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) ''' t2 = MyTemplate(''''' {{{{ {{var}} ''') print('MATCHES: ', t2.pattern.findall(t2.template)) print('SUBSTITUTED: ', t2.safe_substitute(var='replacement'))
輸出:
\$(?: (?P<escaped>\$) | # Escape sequence of two delimiters (?P<named>[_a-z][_a-z0-9]*) | # delimiter and a Python identifier {(?P<braced>[_a-z][_a-z0-9]*)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) MATCHES: [('{{', '', '', ''), ('', 'var', '', '')] SUBSTITUTED: {{ replacement
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
python入門while循環(huán)語句理解學(xué)習(xí)
這篇文章主要介紹了python入門while循環(huán)語句理解學(xué)習(xí),文中附含詳細(xì)圖文示例教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-09-09Tensorflow設(shè)置顯存自適應(yīng),顯存比例的操作
今天小編就為大家分享一篇Tensorflow設(shè)置顯存自適應(yīng),顯存比例的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02Python 的 f-string 可以連接字符串與數(shù)字的原因解析
這篇文章主要介紹了Python 的 f-string 可以連接字符串與數(shù)字的原因解析,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02