【python cookbook】替换字符串中的子串(使用Template)

任务:

给定一个字符串 通过查询一个字符串替换字典 将字符串中被标记的子字符串替换掉

解决方案

Python2.4提供了新的string.Template类 可以完成 

实现方法

#!/usr/bin/python
# -*- coding: utf-8 -*-

#替换字符串中的子串 使用Template

import string
def sub_replace(str):
    #从字符串生成模版 其中标识符被$标记
    new_style = string.Template(str)
    #给模版的substitute方法传入一个字典参数并调用之
    print new_style.substitute({'thing':5})
    print new_style.substitute({'thing':'test'})
    #给substitute方法传入关键字参数
    print new_style.substitute(thing = 5)
    print new_style.substitute(thing = 'test')

if __name__ == '__main__'():
    str = 'this is $thing'
    sub_replace(str)

 

如果需要输出$ 可用$$ 来代表$

如果那些需要被替换的标志后面直接跟上用于替换的文本或者数字 用{}括起来

str ='''Please accept this $$5 coupon
                                      {name}Inn'''
str_template = string.Template(str)
print str_template.substitute({'name':'Sleepy'})

为了给 substitute准备一个字典做参数,最简单的是设定一些本地变量 然后将这些变量交给locals()(此函数将创建一个字典,字典的key是本地变量 本地变量可以通过key来访问)

msg = string.Template('the square of $number is $square')
for number in range(10):
    square = number * number
    print msg.substitute(locals())

也可使用关键字参数。直接将值传给substitute

msg = string.Template('the square of $number is $square')
for number in range(10):
    print msg.substitute(number=i,square=i*i)

也可同时使用以上两种 但是冲突时,关键字优先

比如

msg = string.Template('an $adj $msg')
adj = 'interesting'
print msg.substitute(locals(),msg='message')

转载于:https://www.cnblogs.com/cacique/archive/2012/07/27/2611464.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值