Python中的字符串模板类?

Python字符串模板类用于创建简单的模板字符串。Python模板字符串最早是在python 2.4中引入的。Python字符串模板是通过将模板字符串作为参数传递给其构造函数而创建的。其中字符串格式运算符用于替代百分号,而模板对象使用美元符号。

模板类提供了三种从模板创建字符串的方法-

  • 类string.Template(template)-构造函数采用单个参数,即模板字符串。

  • replace(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 as substitute argument

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)

结果

In the winter, Rajesh drinks Coffee.

打印模板字符串

template对象中的template属性返回模板字符串。

from string import Template

t = Template('$when, $who $action $what.')
print('Template String: ', t.template)

结果

Template String: $when, $who $action $what.

转义$符号

from string import Template

t = Template('$$ is called $name')
s=t.substitute(name='Dollar')
print(s)

结果

$ is called Dollar${identifier} example${<identifier>} is equivalent to $<identifier>

当有效的标识符字符位于占位符之后但不属于占位符时,例如${noun}化,则为必填项。

from string import Template
t = Template('$noun adjective is ${noun}ing')
s = t.substitute(noun='Test')
print(s)

结果

Test adjective is Testing