zoukankan      html  css  js  c++  java
  • 【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')
  • 相关阅读:
    690. Employee Importance 员工重要性
    682. Baseball Game 棒球比赛计分
    680. Valid Palindrome II 有效的回文2
    553. Optimal Division 最佳分割
    服务器oracle数据库定时备份
    数据类型和抽象数据类型
    静态链表和动态链表的区别:
    it网站
    java 移动开发获取多级下拉框json数据的类和mobile-select-area插件
    redis持久化之aof篇
  • 原文地址:https://www.cnblogs.com/cacique/p/2611464.html
Copyright © 2011-2022 走看看