python的Template

本文介绍了 Python 中的 Template 模块,详细解释了如何使用 $ 符号进行变量替换,以及 Template 类中的两个关键方法:substitute 和 safe_substitute 的用法与区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

Template属于string中的一个类,所以要使用的话要在头部引入:
1 from string import Template
模板替换变量采用的是$符号,而不是%,它的使用要遵循以下规则:
  • $$ 是需要规避,已经采用一个单独的 $代替($$相当于输出$,而不是变量)
  • $identifier 变量由一个占位符替换(key),key去匹配变量 "identifier" 
  • ${identifier}相当于 $identifier. 它被用于当占位符后直接跟随一个不属于占位符的字符,列如 "${noun}ification"
Template中有两个重要的方法:substitute和safe_substitute,如下标红的方法名
 1 class string.Template(template)
 2 The constructor takes a single argument which is the template string.
 3 
 4 substitute(mapping, **kwds)
 5 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.
 6 
 7 safe_substitute(mapping, **kwds)
 8 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.
 9 
10 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.
 测试代码--规则:
1 s1 = Template('$who likes $what')
2 print(s1.substitute(who='tim', what='kung pao'))
3 
4 s2 = Template('${who}likes $what')
5 print(s2.substitute(who='tim', what='kung pao'))
6 
7 s3 = Template('$$who likes $what')
8 print(s3.substitute(who='tim', what='kung pao'))
输出:
tim likes kung pao
timlikes kung pao
$who likes kung pao
测试代码--safe_substitute和substitute区别:
1 d = dict(who='java')
2 print(Template('$who need $100').safe_substitute(d))
3 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

 

转载于:https://www.cnblogs.com/tiecheng/p/6018512.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值