string模块中包含了一个很有用的Template类,可以先写好字符串模板,后期使用的时候直接替换就可以了。
模板中使用$作为占位符前缀,使用{}包裹占位符以支持间断的标量名,使用$$转义$。例如:
>>>from string importTemplate
>>> t =Template('${village}folk send $$10 to $cause.')
>>> t.substitute(village='Nottingham', cause='the ditch fund')
'Nottinghamfolk send $10 to the ditch fund.'
如果字典中没有提供相应的替换参数,substitute()将抛出KeyError异常。
如果只想替换部分参数,可以使用safe_substitute()方法。例如
>>> 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的子类中可以自定义分隔符,例如,下面的批量重命名使用%作为分隔符
>>> import time, os.path
>>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
>>> class BatchRename(Template):
... delimiter = '%'
>>> fmt = raw_input('Enter rename style (%d-date %n-seqnum %f-format): ')
Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f >>> t = BatchRename(fmt)
>>> date = time.strftime('%d%b%y')
>>> for i, filename in enumerate(photofiles):
... base, ext = os.path.splitext(filename)
... newname = t.substitute(d=date, n=i, f=ext)
... print '{0} --> {1}'.format(filename, newname) img_1074.jpg --> Ashley_0.jpg
img_1076.jpg --> Ashley_1.jpg
img_1077.jpg --> Ashley_2.jpg