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

yipeiwu_com5年前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程序设计有所帮助。

相关文章

python 拼接文件路径的方法

如下所示: <code class="language-python">import os base_dir = os.path.dirname(__file__)...

Python数据分析matplotlib设置多个子图的间距方法

注意,要看懂这里,必须具备简单的Python数据分析知识,必须知道matplotlib的简单使用! 例1: plt.subplot(221) # 第一行的左图 plt.subplo...

使用PIL(Python-Imaging)反转图像的颜色方法

利用PIL将图片转换为黑色与白色反转的图片,下面笔者小白介绍如何实现。 解决方案一: from PIL import Image import PIL.ImageOps #读入图...

Django中提示消息messages的设置方式

1. 引入messages模块 from django.contrib import messages 2. 把messages写入view中 @csrf_exempt def...

python获取指定日期范围内的每一天,每个月,每季度的方法

1.获取所有天,返回一个列表: def getBetweenDay(begin_date): date_list = [] begin_date = datetime.dat...