• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

cynchanpin

  • 博客园
  • 联系
  • 订阅
  • 管理

View Post

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

字符串模板的安全替换(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! 




posted on 2017-07-02 12:03  cynchanpin  阅读(1596)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3