Python 的标准库有 string 模块。它提供了执行不同字符串操作的功能。
String 模板类
string 模块中的 Template 类提供了一种动态格式化字符串的替代方法。Template 类的好处之一是能够自定义格式规则。
Template 的实现使用正则表达式来匹配有效模板字符串的一般模式。有效的模板字符串或占位符由两部分组成:$ 符号后跟有效的 Python 标识符。
您需要创建一个 Template 类的对象,并使用模板字符串作为构造函数的参数。
接下来调用 Template 类的 substitute() 方法。它将作为参数提供的值代替模板字符串。
String 模板类示例
from string import Template
temp_str = "My name is $name and I am $age years old"
tempobj = Template(temp_str)
ret = tempobj.substitute(name='Qikepu', age=43)
print (ret)
它将产生以下输出 -
My name is Qikepu and I am 43 years old
解包字典键值对
我们还可以从字典中解压缩键值对来替换值。
例
from string import Template
student = {'name':'Qikepu', 'age':43}
temp_str = "My name is $name and I am $age years old"
tempobj = Template(temp_str)
ret = tempobj.substitute(**student)
print (ret)
它将产生以下输出 -
My name is Qikepu and I am 43 years old