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

yipeiwu_com6年前Python基础

本文实例讲述了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()

运行结果:

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python字符串操作技巧汇总》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》及《Python入门与进阶经典教程》。

希望本文所述对大家Python程序设计有所帮助。

相关文章

wxPython电子表格功能wx.grid实例教程

本文实例为大家分享了wxPython电子表格功能的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python #encoding: utf8 import wx...

详解python3中用HTMLTestRunner.py报ImportError: No module named 'StringIO'如何解决

详解python3中用HTMLTestRunner.py报ImportError: No module named 'StringIO'如何解决

python3中用HTMLTestRunner.py报ImportError: No module named 'StringIO'的解决方法: 1.原因是官网的是python2语法写的...

浅析Python中将单词首字母大写的capitalize()方法

 capitalize()方法返回字符串的一个副本,只有它的第一个字母大写。对于8位的字符串,这个方法与语言环境相关。 语法 以下是capitalize()方法的语法: s...

Python常用的json标准库

当请求 headers 中,添加一个name为 Accept,值为 application/json 的 header(也即“我”(浏览器)接收的是 json 格式的数据),这样,向服务...

python 通过手机号识别出对应的微信性别(实例代码)

python 通过手机号识别出对应的微信性别,具体代码如下所述: def getGender(self,tel): self.d(resourceId="com.tencent....