源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python编程之字符串模板(Template)用法实例分析

  • 时间:2020-12-28 04:47 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python编程之字符串模板(Template)用法实例分析
本文实例讲述了Python编程之字符串模板(Template)用法。分享给大家供大家参考,具体如下:
#coding=utf8
'''''
字符串格式化操作符,需要程序员明确转换类型参数,
比如到底是转成字符串、整数还是其他什么类型。
新式的字符串模板的优势是不用去记住所有相关细节,
而是像shell风格的脚本语言里面那样使用美元符号($).
由于新式的字符串引进Template对象,
Template对象有两个方法:substitute()、safe_substitute()。
substitute()更为严谨,在key缺少的情况下会报一个KeyError的异常。
safe_substitute()在缺少key的情况下,直接原封不动的把字符串显示出来。
'''
#导入Template对象
from string import Template
def stringTemplate():
  #创建一个Template实例tmp
  tmp=Template("I have ${yuan} yuan,I can buy ${how} hotdog")
  yuanList=[1,5,8,10,12,13]
  for yu in yuanList:
    #substitute()按照Template中string输出
    #并给相应key赋值
    Substitute= tmp.substitute(yuan=yu,how=yu)
    print Substitute
  print
  for yu in yuanList:
    #使用substitute函数缺少key值包KeyError
    try:
      lackHow= tmp.substitute(yuan=yu)
      print lackHow
      print
    except KeyError,e:
      print "substitute lack key ",e
  print
  for yu in yuanList:
    #safe_substitute()在缺少key的情况下
    #直接原封不动的把字符串显示出来。
    safe_substitute= tmp.safe_substitute(yuan=yu)
    print safe_substitute
  print
#调用stringTemplate函数
stringTemplate()

运行结果: [img]http://files.jb51.net/file_images/article/201707/2017722101813762.jpg?2017622101838[/img] 更多关于Python相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/636.htm]Python字符串操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/788.htm]Python编码操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/663.htm]Python数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/642.htm]Python函数使用技巧总结[/url]》及《[url=http://www.1sucai.cn/Special/520.htm]Python入门与进阶经典教程[/url]》。 希望本文所述对大家Python程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部