[python库]标准库--string的Template
程序员文章站
2024-01-16 21:37:52
...
本文转自:https://www.cnblogs.com/tiecheng/p/6018512.html,请点击链接查看原文,尊重楼主版权。
Template模块,可以用来制作网页、文本模板,非常的方便。
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改成$100substitute比较严格,必须每一个占位符都找到对应的变量,不然就会报错,而safe_substitute则会把未找到的$XXX直接输出
参考资料:
https://docs.python.org/3.4/library/string.html#template-strings
https://my.oschina.net/u/241670/blog/309856上一篇: Android 判定网络连接状态 以及监听网络链接状态的变化
下一篇: ffmpeg处理视频命令
推荐阅读
-
[python库]标准库--string的Template
-
Python3.6连接Oracle数据库的方法详解
-
Python数据可视化高级库pyecharts的用法,相关环境的安装部署和第一个简单的可视化柱状统计图
-
python之Matplotlib库的简单操作
-
python之matplotlib库的基本操作
-
BinaryTree:学习二叉树的Python库
-
忘记ftp密码使用python ftplib库暴力破解密码的方法示例
-
oauth - 有没有集成多家第三方平台的用户管理php,python库/微框架?
-
解析HTML的Python库--Requests-HTML推荐
-
Python中用memcached来减少数据库查询次数的教程