• 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



  • 相关阅读:
    10)添加路径并显示
    ueditor使用-图片上传正常,图片显示异常404
    连接mysql出错
    曾经踩过的坑--浏览器兼容-history
    css样式继承(转)
    超链接中文字超长使用省略号代替
    bootstrap-datetimepicker出现时间选择时年份显示1899年的异常
    angularJS:ng-repeat作用域及父作用域调用$parent
    $parse:表达式转换
    angularJS factory中包含xhr时,通过promise获取结果
  • 原文地址:https://www.cnblogs.com/fireflow/p/4864902.html
Copyright © 2020-2023  润新知