zoukankan      html  css  js  c++  java
  • Python

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




    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    数组的简单操方法
    Java Script 流程控制语句(if判断、switch选择和循环)
    HTML,表单
    CSS盒子定位
    CSS基础选择器简单介绍
    java操作redis
    ios选择城市
    格式化java对象为json
    java冒泡排序法
    mongoDB group分组
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4728384.html
Copyright © 2011-2022 走看看