Template
字符串模板,用于替换字符串中的变量。
模板字符串支持基于$的替换,并遵循以下规则:
$$:被替换为$
$变量:标识符仅限以下划线或者字符开头的字母数字字符串(包括下划线),字符后的第一个非标识符字符终止此占位符规
${变量}:等同于$变量,当有效标识符位于占位符之后但是不属于占位符是,必须用此种方式,比如${age}age
此类的方法:
substitute(mapping={}, /, **kwds)
:执行模板替换并返回一个新字符串。映射是任何类似于字典的对象,其键与模板中的占位符匹配。safe_substitute(mapping={}, /, **kwds)
:与substitute()相似。不同之处在于,如果映射和kwds中缺少占位符,而不是引发KeyError异常,则原始占位符将完整显示在结果字符串中。
示例-替换字符串中占位符:
from string import Template
def test_example():
template = Template("$who like $what")
d = {'who':"he", "what":"running"}
template_new = template.substitute(d)
print(temp