Python:Template使用指南
来源:互联网 发布:淘宝国际卖家 编辑:程序博客网 时间:2024/06/08 05:39
17年7月第5篇日志
七月快要结束,八月马上就要开始。最近人工智能的势头越来越过,不过这个浪潮下谁留下来,谁能踏实作出新的成就,一切都未可知。
本周带来的博客主要讲解Template的使用,这篇博客是基于python3写的,因为最近在做微信的项目采用的语言就是python 3,下面进入正题。
Template无疑是一个好东西,可以将字符串的格式固定下来,Template属于string中的一个类,所以要使用的话可以用以下方式调用:
from string import Template
template 有个特殊的标识符
from string import Templates=Template("There $a and ${b}s")print (s.substitute(a='apple',b='banana'))print (s.safe_substitute(a='apple',b='banbana'))
运行结果:
PycharmProjects/untitled/reply.pyThere apple and bananasThere apple and banbanasProcess finished with exit code 0
Template还可以通过字典来直接传递数据:
from string import Templates=Template("There $a and ${b}s")d={'a':'apple','b':'banbana'}print(s.substitute(d))
运行结果:
from string import Templates=Template("There $a and ${b}s")d={'a':'apple','b':'banbana'}print(s.substitute(d))
Template的实现方式是首先通过Template初始化一个字符串。这些字符串中包含了一个个key。通过调用substitute或safe_subsititute,将key值与方法中传递过来的参数对应上,从而实现在指定的位置导入字符串。这个方式的一个好处是不用像print ‘%s’之类的方式,各个参数的顺序必须固定,只要key是正确的,值就能正确插入。
substitute是一个严肃的方法,如果有key没有输入,那就一定会报错。虽然会很难看,但是可以发现问题。safe_substitute则不会报错,而是将$xxx直接输入到结果字符串中。例如:
from string import Templates=Template("There $a and ${b}s")d={'a':'apple'}#print(s.substitute(d))print(s.safe_substitute(d))
结果:
PycharmProjects/untitled/reply.pyThere apple and ${b}sProcess finished with exit code 0
通过safe_substitute可以保证你的程序总是对的。
同时在Template中还可以通过继承重写的方式,进行一些个性化的修改。通过修改delimiter字段可以将$字符改变为其他字符如“#”,不过新的标示符需要符合正则表达式的规范。通过修改idpattern可以修改key的命名规则,比如说规定第一个字符开头必须是a,这对规范命名倒是很有好处。当然,这也是通过正则表示实现的。
from string import Templateclass MyTemplate(Template): delimiter = "#" idpattern = "[a][_a-z0-9]*"def test(): s='#aa is not #ab' t=MyTemplate(s) d={'aa':'apple','ab':'banbana'} print (t.substitute(d))if __name__=='__main__': test()
上面就是对于Template的详细的讲解,希望能够给大家带来帮助,上面的所示内容,均通过代码的实际验证,可以保证准确无误。
- python的Template使用指南
- Python:Template使用指南
- python的Template使用指南
- python template
- python Template
- Python Template Demo
- python string Template
- nagios python template
- [笔记]python template 模板
- Python线程使用指南
- MySQLdb for Python使用指南
- Python BeautifulSoup4 使用指南
- python logging 模块使用指南
- Python Hashmap/Dictionary 使用指南
- Python logging使用指南
- <python> ftp 使用指南
- python:BeautifulSoup 模块使用指南
- python:BeautifulSoup 模块使用指南
- 函数返回指针数组
- 系统集成项目管理工程师学习笔记(三)项目管理的一般知识
- 0517
- 字符串转换成十进制整数
- vivo2017实习生编程题
- Python:Template使用指南
- Java List集合使用方法介绍(2)——公告管理
- C++ 简易string类实现(五)-进一步抽象
- 多路查找树(B树)
- Linux中软链接和硬链接的区别(笔记)
- 台湾大学林轩田机器学习基石课程学习笔记11 -- Linear Models for Classification
- 人员签到程序
- 宏润年
- undefined和null的区别