Python的string模块中的Template类字符串模板用法


Posted in Python onJune 27, 2016

string.Template()
string.Template()内添加替换的字符, 使用"$"符号, 或 在字符串内, 使用"${}"; 调用时使用string.substitute(dict)函数.
可以通过继承"string.Template", 覆盖变量delimiter(定界符)和idpattern(替换格式), 定制不同形式的模板.

代码:

# -*- coding: utf-8 -*- 

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个没有进行替换.

正则替换

string.Template的pattern是一个正则表达式, 可以通过覆盖pattern属性, 定义新的正则表达式.
如: 使用新的定界符"{{", 把{{var}}作为变量语法.

代码:

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

字符串模板的安全替换(safe_substitute)
字符串模板(sting.Template), 替换时, 使用substitute(), 未能提供模板所需的全部参数值时, 会发生异常.
如果使用safe_substitute(), 即安全替换, 则会替换存在的字典值, 保留未存在的替换符号.

代码:

import string 
 
values = {'var' : 'foo'} 
 
t = string.Template('''''$var is here but $ missing is not provided! ''') 
 
 
try: 
  print 'substitute() : ', t.substitute(values) 
except ValueError as err: 
  print 'Error:', str(err) 
   
print 'safe_substitude() : ', t.safe_substitute(values)

输出:

substitute() : Error: Invalid placeholder in string: line 1, col 18 
safe_substitude() : foo is here but $ missing is not provided!

Python 相关文章推荐
Python中如何获取类属性的列表
Dec 26 Python
Django自定义分页与bootstrap分页结合
Feb 22 Python
Django如何开发简单的查询接口详解
May 17 Python
这可能是最好玩的python GUI入门实例(推荐)
Jul 19 Python
pycharm配置当鼠标悬停时快速提示方法参数
Jul 31 Python
python防止随意修改类属性的实现方法
Aug 21 Python
pygame库实现俄罗斯方块小游戏
Oct 29 Python
win10下python2和python3共存问题解决方法
Dec 23 Python
双向RNN:bidirectional_dynamic_rnn()函数的使用详解
Jan 20 Python
flask开启多线程的具体方法
Aug 02 Python
python爬虫构建代理ip池抓取数据库的示例代码
Sep 22 Python
jupyter notebook保存文件默认路径更改方法汇总(亲测可以)
Jun 09 Python
Python的Flask框架及Nginx实现静态文件访问限制功能
Jun 27 #Python
总结网络IO模型与select模型的Python实例讲解
Jun 27 #Python
结合Python的SimpleHTTPServer源码来解析socket通信
Jun 27 #Python
Python的Tornado框架的异步任务与AsyncHTTPClient
Jun 27 #Python
深入解析Python中的descriptor描述器的作用及用法
Jun 27 #Python
Python中的字符串查找操作方法总结
Jun 27 #Python
解析Python中的__getitem__专有方法
Jun 27 #Python
You might like
php下实现伪 url 的超简单方法[转]
2007/09/24 PHP
PHP的switch判断语句的“高级”用法详解
2014/10/01 PHP
thinkPHP下ueditor的使用方法详解
2015/12/26 PHP
IE8 引入跨站数据获取功能说明
2008/07/22 Javascript
Js 刷新框架页的代码
2010/04/13 Javascript
html中使用javascript调用本地程序(exe、doc等)实现代码
2013/04/26 Javascript
对js关键字命名的疑问介绍
2014/04/25 Javascript
js调试系列 源码定位与调试[基础篇]
2014/06/18 Javascript
js识别不同浏览器基于userAgent做判断
2014/07/29 Javascript
加载列表时jquery获取ul中第一个li的属性
2014/11/02 Javascript
浅析js中substring和substr的方法
2015/11/09 Javascript
JavaScript基础篇(3)之Object、Function等引用类型
2015/11/30 Javascript
JS简单实现tab切换效果的多窗口显示功能
2016/09/07 Javascript
jquery动态添加文本并获取值的方法
2016/10/12 Javascript
AngularJS过滤器filter用法分析
2016/12/11 Javascript
微信禁止下拉查看URL的处理方法
2017/09/28 Javascript
Vue精简版风格概述
2018/01/30 Javascript
Javascript实现异步编程的过程
2018/06/18 Javascript
利用Webpack实现小程序多项目管理的方法
2019/02/25 Javascript
JS中FormData类实现文件上传
2020/03/27 Javascript
python统计字符串中指定字符出现次数的方法
2015/04/04 Python
在Django中限制已登录用户的访问的方法
2015/07/23 Python
Window 64位下python3.6.2环境搭建图文教程
2018/09/19 Python
python2和python3实现在图片上加汉字的方法
2019/08/22 Python
用python拟合等角螺线的实现示例
2019/12/27 Python
Python爬虫抓取指定网页图片代码实例
2020/07/24 Python
python正则表达式 匹配反斜杠的操作方法
2020/08/07 Python
日本网路线上商品代购服务:转送JAPAN
2016/08/05 全球购物
世界上最具创新性的增强型知名运动品牌:Proviz
2018/04/03 全球购物
益模软件Java笔试题
2012/03/27 面试题
趣味比赛活动方案
2014/02/15 职场文书
解放思想演讲稿
2014/09/11 职场文书
沙滩主题婚礼活动策划方案
2014/09/15 职场文书
党员发展大会主持词
2015/07/03 职场文书
2016年感恩母亲节活动总结
2016/04/01 职场文书
写给医护人员的一封感谢信
2019/09/16 职场文书