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

相关文章

Python 函数list&read&seek详解

Python 函数list&read&seek详解

一、函数list (1)定义:用打开的文件作为参数,把文件内的每一行内容作为一个元素 (2)格式:list(文件) (3)例子: with open(r"test01.txt",'r...

详解Python循环作用域与闭包

前言 首先来看一段代码 x_list = [i for i in range(30)] y_list = [i for i in range(10, 20)] for y in y...

老生常谈Python startswith()函数与endswith函数

函数:startswith() 作用:判断字符串是否以指定字符或子字符串开头 一、函数说明 语法:string.startswith(str, beg=0,end=len(string)...

python数据分析数据标准化及离散化详解

python数据分析数据标准化及离散化详解

本文为大家分享了python数据分析数据标准化及离散化的具体内容,供大家参考,具体内容如下 标准化 1、离差标准化 是对原始数据的线性变换,使结果映射到[0,1]区间。方便数据的处理。消...

Python3.7 读取 mp3 音频文件生成波形图效果

Python3.7 读取 mp3 音频文件生成波形图效果

测试环境为Windows 10 系统,Python3.7,转换需要提前安装pydub、ffmpeg,安装和加入环境变量配置方法自行解决,至于缺少的包直接 pip install xx 搞...