Template模块,可以用来制作web页面的模板,非常的方便。

Template属于string中的一个类,所以要使用的话要在头部引入:

 from string import Template

模板替换变量采用的是$符号,而不是%,它的使用要遵循以下规则:

  • $$ 是需要规避,已经采用一个单独的 $代替($$相当于输出$,而不是变量)
  • $identifier 变量由一个占位符替换(key),key去匹配变量 "identifier"
  • ${identifier}相当于 $identifier. 它被用于当占位符后直接跟随一个不属于占位符的字符,列如 "${noun}ification"

Template中有两个重要的方法:substitute和safe_substitute,如下标红的方法名

 class string.Template(template)
The constructor takes a single argument which is the template string. substitute(mapping, **kwds)
Performs the template substitution, returning a new string. mapping is any dictionary-like object with keys that match the placeholders in the template. Alternatively, you can provide keyword arguments, where the keywords are the placeholders. When both mapping and kwds are given and there are duplicates, the placeholders from kwds take precedence. safe_substitute(mapping, **kwds)
Like substitute(), except that if placeholders are missing from mapping and kwds, instead of raising a KeyError exception, the original placeholder will appear in the resulting string intact. Also, unlike with substitute(), any other appearances of the $ will simply return $ instead of raising ValueError. While other exceptions may still occur, this method is called “safe” because substitutions always tries to return a usable string instead of raising an exception. In another sense, safe_substitute() may be anything other than safe, since it will silently ignore malformed templates containing dangling delimiters, unmatched braces, or placeholders that are not valid Python identifiers.

测试代码--规则:

 s1 = Template('$who likes $what')
print(s1.substitute(who='tim', what='kung pao')) s2 = Template('${who}likes $what')
print(s2.substitute(who='tim', what='kung pao')) s3 = Template('$$who likes $what')
print(s3.substitute(who='tim', what='kung pao'))

输出:

tim likes kung pao
timlikes kung pao
$who likes kung pao

测试代码--safe_substitute和substitute区别:

 d = dict(who='java')
print(Template('$who need $100').safe_substitute(d))
print(Template('$who need $100').substitute(d))

输出:

java need $100
Traceback (most recent call last):

使用safe_substitute可以正常输出,而使用substitute会出错,需要把$100改成$$100

substitute比较严格,必须每一个占位符都找到对应的变量,不然就会报错,而safe_substitute则会把未找到的$XXX直接输出

参考资料:https://docs.python.org/3.4/library/string.html#template-strings

  https://my.oschina.net/u/241670/blog/309856

python的Template的更多相关文章

  1. Python中Template使用的一个小技巧

    Python中Template是string中的一个类,可以将字符串的格式固定下来,重复利用. from string import Template s = Template("there ...

  2. python的Template使用指南

    本文主要讲解了python中Template使用方法以及使用技巧,非常实用,有需要的朋友可以参考下: Template无疑是一个好东西,可以将字符串的格式固定下来,重复利用.同时Template也可以 ...

  3. Python Jinja2 Template: YAML File Cisco Example Tutorial

    原文链接:http://networkbit.ch/python-jinja-template/ template.txt如下: hostname {{ name }} interface Loopb ...

  4. python Template中substitute()的使用

    在python中Template可以将字符串的格式固定下来,重复利用. Template属于string中的一个类,要使用他的话可以用以下方式调用: from string import Templa ...

  5. 使用Template格式化Python字符串

    对Python字符串,除了比较老旧的%,以及用来替换掉%的format,及在python 3.6中加入的f这三种格式化方法以外,还有可以使用Template对象来进行格式化. from string ...

  6. python中常用的函数与库一

    1, collections.deque 在python里如果我们用列表作为队列使用也是可以的,只是当从队尾删除或者增加元素的时候是很快的,但是从队首删除或者增加元素则要慢得多,这是因为在队首进行操作 ...

  7. python简单爬虫定时推送同花顺直播及荐股至邮箱

    1.初衷:实践 2.技术:python requests Template 3.思路:根据直播页面获取评价最高的前十博主,定时爬行最新的消息和实战股票 4.思路:python 编辑简单邮件html模板 ...

  8. Python day 02

    基础&运算符 今日概要 循环 字符串格式化 运算符 编码 内容回顾 & 补充 内容回顾 计算机基础 解释器python 2 和 python 3 语法 print input if / ...

  9. Testing shell commands from Python

    如何测试shell命令?最近,我遇到了一些情况,我想运行shell命令进行测试,Python称为万能胶水语言,一些自动化测试都可以完成,目前手头的工作都是用python完成的.但是无法从Python中 ...

随机推荐

  1. coreseek安装

    一.  Sphinx简介 Sphinx是由俄罗斯人Andrew Aksyonoff开发的一个全文检索引擎.意图为其他应用提供高速.低空间占用.高结果 相关度的全文搜索功能.Sphinx可以非常容易的与 ...

  2. React.js入门笔记(再续):评论框的实现

    本案例来自React.js中文官网对应内容. 一. 运行环境 <link rel="stylesheet" type="text/css" href=&q ...

  3. 跟我一起学习VIM

    跟我一起学习VIM - The Life Changing Editor   前两天同事让我在小组内部分享一下VIM,于是我花了一点时间写了个简短的教程.虽然准备有限,但分享过程中大家大多带着一种惊叹 ...

  4. 387. First Unique Character in a String

    Given a string, find the first non-repeating character in it and return it's index. If it doesn't ex ...

  5. HTML中的SVG

    HTML5中的SVG是Scalable Vector Graphic的简称,是一种用来绘制矢量图的HTML5标签,由万维网联盟定制,是一个基于可扩展标记语言,用于绘制二维可缩放矢量图形. 是一种使用X ...

  6. Bubble Cup 8 finals A. Fibonotci (575A)

    题意: 定义类循环序列为 长度无限,且除了有限个元素外,均满足s[i] ≡ s[i mod N] (i≥N). 现在有数列F,定义为 F[i] = s[i-2]*F[i-1] + s[i-1]*F[i ...

  7. synthesize的作用

    @synthesize是对属性的实现,实际上就是制定setter和getter操作的实例变量的名称   举个栗子: @synthesize array;  默认操作的实例变量和属性同名 @synthe ...

  8. npm 发布到远程资源库

    一.npm 发布到远程资源库 1.创建package.json Package.json 属性说明 name - 包名. version - 包的版本号. description - 包的描述. ho ...

  9. XSS(跨站脚本攻击)的最全总结

    从OWASP的官网意译过来,加上自己的理解,算是比较全面的介绍.有兴趣的可私下交流. XSS 跨站脚本攻击 ============================================== ...

  10. 【bzoj4721】[Noip2016]蚯蚓

    题目描述 本题中,我们将用符号[c]表示对c向下取整,例如:[3.0」= [3.1」=[3.9」=3.蛐蛐国最近蚯蚓成灾了!隔壁跳蚤国的跳蚤也拿蚯蚓们没办法,蛐蛐国王只好去请神刀手来帮他们消灭蚯蚓.蛐 ...