python string模块template_Python - 定制pattern的string模板(template) 详解
定制pattern的string模板(template) 詳解
本文地址:?http://blog.csdn.net/caroline_wendy/article/details/28625179
string.Template的pattern是一個正則表達(dá)式, 可以通過覆蓋pattern屬性, 定義新的正則表達(dá)式.
如: 使用新的定界符"{{", 把{{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\{\{) | # Escape sequence of two delimiters
(?P[_a-z][_a-z0-9]*)\}\} | # delimiter and a Python identifier
{(?P[_a-z][_a-z0-9]*)}\}\} | # delimiter and a braced identifier
(?P) # Other ill-formed delimiter exprs
)
‘‘‘
t2 = MyTemplate(‘‘‘
{{{{
{{var}}
‘‘‘)
print(‘MATCHES: ‘, t2.pattern.findall(t2.template))
print(‘SUBSTITUTED: ‘, t2.safe_substitute(var=‘replacement‘))
輸出:
\$(?:
(?P\$) | # Escape sequence of two delimiters
(?P[_a-z][_a-z0-9]*) | # delimiter and a Python identifier
{(?P[_a-z][_a-z0-9]*)} | # delimiter and a braced identifier
(?P) # Other ill-formed delimiter exprs
)
MATCHES: [(‘{{‘, ‘‘, ‘‘, ‘‘), (‘‘, ‘var‘, ‘‘, ‘‘)]
SUBSTITUTED:
{{
replacement
總結(jié)
以上是生活随笔為你收集整理的python string模块template_Python - 定制pattern的string模板(template) 详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mate Xs 2折叠旗舰绝配!华为M-
- 下一篇: python解释器的提示符是shell嘛