python字符串模板_Python - 定制语法的string模板(template) 详解

定制语法的string模板(template) 详解

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值