Template属于string中的一个类。
Template字符串支持基于$的替换,使用以下规则:
- $$是一个转义字符;它被替换成单个$
- $identifier命名一个替换占位符,该占位符与"identifier"的映射键匹配。默认情况"identifier"被限制为任何以 下划线或ASCII字母开头的不区分大小写的ASCII字母数字字符串(包括下划线)。$字符之后的第一个非标识符字符终止此占位符规范。
- ${identifier}等价于$identifier。当有效的标识符字符跟在占位符后面但不是占位符的一部分时,如“${noun}ification”,则需要使用该参数。
字符串中任何其他$的出现都将导致引发ValueError。
它的主要实现方式为$xxx,其中xxx是满足python命名规则的字符串,即不能以数字开头,不能为关键字等。如果$xxx需要和其他字符串接触时,可用{}将xxx包裹起来 。例如,aaa${xxx}aaa
两个函数:
substitute
(mapping={}, /, **kwds)
执行模板替换,返回一个新的字符串。mapping是任何带有匹配模板中占位符的键的dictionary-like对象。或者,您可以提供关键字参数,其中关键字是占位符。当同时给出了mapping和kwds,并且存在副本时,来自kwds的占位符将优先
safe_substitute
(mapping={}, /, **kwds)
与substitute()类似,不同的是,如果mapping和kwds中缺少占位符,那么原始的占位符将完整地出现在结果字符串中,而不是引发KeyError异常。另外,与substitute()不同,任何其他出现的$都将简单地返回$,而不是引发ValueError。
例子:
>>> from string import Template >>> s = Template('$who likes $what') >>> s.substitute(who='tim', what='kung pao') 'tim likes kung pao' >>> d = dict(who='tim') >>> Template('$who likes $what').safe_substitute(d) 'tim likes $what'
>>> d = dict(who='tim') >>> Template('Give $who $100').substitute(d) Traceback (most recent call last): ... ValueError: Invalid placeholder in string: line 1, col 11 #出现错误 >>> Template('$who likes $what').substitute(d) Traceback (most recent call last): ... KeyError: 'what' #出现错误
string — Common string operations — Python 3.10.2 documentation