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數(shù)據(jù)分析必會的Pandas技巧匯總
用Python做數(shù)據(jù)分析光是掌握numpy和matplotlib可不夠,numpy雖然能夠幫我們處理處理數(shù)值型數(shù)據(jù),但很多時候,還有字符串,還有時間序列等,比如:我們通過爬蟲獲取到了存儲在數(shù)據(jù)庫中的數(shù)據(jù),一些Pandas必會的用法,讓你的數(shù)據(jù)分析水平更上一層樓2021-08-08
python函數(shù)調(diào)用,循環(huán),列表復(fù)制實例
這篇文章主要介紹了python函數(shù)調(diào)用,循環(huán),列表復(fù)制實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05
Selenium+Python自動化腳本環(huán)境搭建的全過程
說到自動化測試,就不得不提大名鼎鼎的Selenium,Selenium 是如今最常用的自動化測試工具之一,支持快速開發(fā)自動化測試框架,且支持在多種瀏覽器上執(zhí)行測試,下面這篇文章主要給大家介紹了關(guān)于Selenium+Python自動化腳本環(huán)境搭建的相關(guān)資料,需要的朋友可以參考下2021-09-09

