string模板

        string模块中包含了一个很有用的Template类,可以先写好字符串模板,后期使用的时候直接替换就可以了。

         模板中使用$作为占位符前缀,使用{}包裹占位符以支持间断的标量名,使用$$转义$。例如:
  1. 1 >>>from string importTemplate
    2 >>> t =Template('${village}folk send $$10 to $cause.')
    3 >>> t.substitute(village='Nottingham', cause='the ditch fund')
    4 'Nottinghamfolk send $10 to the ditch fund.'
         如果字典中没有提供相应的替换参数,substitute()将抛出KeyError异常。
         如果只想替换部分参数,可以使用safe_substitute()方法。例如
  1. >>> t =Template('Return the $item to $owner.')
    >>> d = dict(item='unladen swallow')
    >>> t.substitute(d)
    Traceback(most recent call last):
    ...
    KeyError:'owner'
    >>> t.safe_substitute(d)
    'Return the unladen swallow to $owner.'
         Template的子类中可以自定义分隔符,例如,下面的批量重命名使用%作为分隔符
  1.  1 >>> import time, os.path
     2 >>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
     3 >>> class BatchRename(Template):
     4 ...     delimiter = '%'
     5 >>> fmt = raw_input('Enter rename style (%d-date %n-seqnum %f-format):  ')
     6 Enter rename style (%d-date %n-seqnum %f-format):  Ashley_%n%f
     7 
     8 >>> t = BatchRename(fmt)
     9 >>> date = time.strftime('%d%b%y')
    10 >>> for i, filename in enumerate(photofiles):
    11 ...     base, ext = os.path.splitext(filename)
    12 ...     newname = t.substitute(d=date, n=i, f=ext)
    13 ...     print '{0} --> {1}'.format(filename, newname)
    14 
    15 img_1074.jpg --> Ashley_0.jpg
    16 img_1076.jpg --> Ashley_1.jpg
    17 img_1077.jpg --> Ashley_2.jpg

     



转载于:https://www.cnblogs.com/fireflow/p/4864902.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值