Python - 定制语法的string模板(template) 详解
2014-06-05 14:04
393 查看
定制语法的string模板(template) 详解
本文地址: http://blog.csdn.net/caroline_wendy/article/details/28614491string模板(template)参考: http://blog.csdn.net/caroline_wendy/article/details/27054263
string.Template()内添加替换的字符, 使用"$"符号, 或 在字符串内, 使用"${}"; 调用时使用string.substitute(dict)函数.
可以通过继承"string.Template", 覆盖变量delimiter(定界符)和idpattern(替换格式), 定制不同形式的模板.
代码:
# -*- coding: utf-8 -*-
'''
Created on 2014.6.5
@author: Administrator
@edition : python 3.3.0, eclipse pydev
'''
import string
template_text = '''
Delimiter : %%
Replaced : %with_underscore
Ingored : %notunderscored
'''
d = {'with_underscore' : 'replaced',
'notunderscored' : 'not replaced'}
class MyTemplate(string.Template):
delimiter = '%'
idpattern = '[a-z]+_[a-z]+'
t = MyTemplate(template_text)
print('Modified ID pattern: ')
print(t.safe_substitute(d))
输出:
Modified ID pattern:
Delimiter : %
Replaced : replaced
Ingored : %notunderscored
注意: 定界符(delimiter)为"%", 替换模式(idpattern)必须包含下划线, 所以第2个没有进行替换.
相关文章推荐
- Python - 定制pattern的string模板(template) 详解
- Python - 定制pattern的string模板(template) 具体解释
- Python 中开发pattern的string模板(template) 实例详解
- C++ - 函数模板定制(function template specialization) 详解 及 代码
- python 字符串模板用法string.Template
- C++ - 函数模板定制(function template specialization) 详解 及 代码
- StringTemplate.net模板语法
- 【phpcms-v9】phpcms-v9中模板载入函数template详解
- StringTemplate.Net 学习笔记(8):加载模板组文件
- StringTemplate.Net 学习笔记(9):深入了解模板组文件
- Python文本常量和模板——string
- FreeMarker模板文件的组成及基本语法详解(二
- python string Template
- python语法31[string的print和format]
- StringTemplate.Net 学习笔记(4):表达式元素语法(下)
- StringTemplate.Net 学习笔记(7):加载模板文件
- FreeMarker模板文件的组成及基本语法详解(一)
- StringTemplate.Net 学习笔记(7):加载模板文件
- FreeMarker模板文件的组成及基本语法详解(二)
- NVelocity模板引擎 vs StringTemplate