Python 中的字符串模板类?
Python 字符串模板类用于创建一个简单的模板字符串。Python 模板字符串最早是在 Python 2.4 中引入的。Python 字符串模板是通过将模板字符串作为参数传递给其构造函数来创建的。其中字符串格式化运算符用于替换百分号,而模板对象使用美元符号。
模板类提供三种方法从模板 − 创建字符串
Class string.Template(template) - 构造函数接受一个参数,即模板字符串。
substitute(mapping, **keywords) - 用字符串值(mapping)替换模板字符串值的方法。Mapping 是一个类似字典的对象,其值可以作为字典访问。如果使用 keywords 参数,则它代表占位符。当同时使用映射和关键字时,关键字优先。如果映射或关键字中缺少占位符,则会引发 keyError。
safe_substitute(mapping, **keywords) - 功能类似于 substitute()。但是,如果映射或关键字中缺少占位符,则默认使用原始占位符,从而避免 KeyError。此外,任何 ‘$’ 出现都会返回美元符号。
模板对象还有一个公开可用的属性−
模板 - 它是传递给构造函数模板参数的对象。尽管不强制执行只读访问,但建议不要在程序中更改此属性。
Python 模板字符串示例
from string import Template
t = Template('$when, $who $action $what.')
s= t.substitute(when='In the winter', who='Rajesh', action='drinks', what ='Coffee')
print(s)
#dictionary 作为替代参数
d = {"when":"In the winter", "who":"Rajesh", "action":"drinks","what":"Coffee"}
s = t.substitute(**d)
print(s)
输出
In the winter, Rajesh drinks Coffee. In the winter, Rajesh drinks Coffee.
safe_substitute()
from string import Template
t = Template('$when, $who $action $what.')
s= t.safe_substitute(when='In the winter', who='Rajesh', action='drinks', what ='Coffee')
print(s)
结果
冬天,Rajesh 喝咖啡。
打印模板字符串
template 对象中的 template 属性返回模板字符串。
from string import Template
t = Template('$when, $who $action $what.')
print('模板字符串:', t.template)
结果
模板字符串:$when, $who $action $what.
转义 $ 符号
from string import Template
t = Template('$$ is called $name')
s=t.substitute(name='Dollar')
print(s)
结果
$ is called Dollar${identifier} 示例
${<identifier>} 等同于 $<identifier>
当有效标识符字符跟在占位符后面但不是占位符的一部分时,例如 ${noun}ification,则需要使用此选项。
from string import Template
t = Template('$noun adjective is ${noun}ing')
s = t.substitute(noun='Test')
print(s)
结果
Test adjective is Testing
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

