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

     



posted @ 2015-10-09 19:33  楚狂人阿飞  阅读(238)  评论(0编辑  收藏  举报