您的位置:首页 > 编程语言 > Python开发

Python - 字符串模板的安全替换(safe_substitute) 详解

2014-05-26 10:14 537 查看

字符串模板的安全替换(safe_substitute) 详解

本文地址: http://blog.csdn.net/caroline_wendy/article/details/27057339

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

代码:
# -*- coding: utf-8 -*-

'''
Created on 2014.5.26

@author: C.L.Wang

Eclipse Pydev python 2.7.5
'''

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!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息