【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')

你可能感兴趣的:(template)