本文共 6245 字,大约阅读时间需要 20 分钟。
>>> from string import Template # 导入模板>>> s = Template("hello, I am ${first_name}.${last_name}") # 构造一个实例>>> s.substitute(first_name="zhou", last_name="digoal") # 替换变量, 返回替换后的字符串'hello, I am zhou.digoal'>>> d=dict() # 使用字典来替换变量.>>> d['first_name']="zhou">>> s.substitute(d) # 注意使用substitute替换的话, 所有的变量必须都被替换.Traceback (most recent call last): File "[参考]", line 1, in File "/usr/local/lib/python3.4/string.py", line 121, in substitute return self.pattern.sub(convert, self.template) File "/usr/local/lib/python3.4/string.py", line 111, in convert val = mapping[named]KeyError: 'last_name'>>> s.safe_substitute(d) # 使用safe_substitute来替换的话, 可以只替换部分或全部或全否变量.'hello, I am zhou.${last_name}'>>> a=dict()>>> s.safe_substitute(a)'hello, I am ${first_name}.${last_name}'>>> s = Template("hello, I am ${first_name}.${123}") # 变量名必须使用合法的变量名, 字母开头. 不能是数字开头.>>> s.safe_substitute(d)'hello, I am zhou.${123}'>>> d['123']="digoal">>> s.safe_substitute(d)'hello, I am zhou.${123}'>>> s.substitute(d) # 数字开头的变量被替换时会报错Traceback (most recent call last): File " ", line 1, in File "/usr/local/lib/python3.4/string.py", line 121, in substitute return self.pattern.sub(convert, self.template) File "/usr/local/lib/python3.4/string.py", line 118, in convert self._invalid(mo) File "/usr/local/lib/python3.4/string.py", line 95, in _invalid (lineno, colno))ValueError: Invalid placeholder in string: line 1, col 27>>> s = Template("hello, I am ${first_name}.${last_name}") # 更换为合法的变量名后, 正常>>> d['last_name']="digoal">>> s.substitute(d)'hello, I am zhou.digoal'>>> s.safe_substitute(d)'hello, I am zhou.digoal'
Templates provide simpler string substitutions as described in . Instead of the normal %-based substitutions, Templates support $-based substitutions, using the following rules:
Any other appearance of $ in the string will result in a being raised.
The module provides a class that implements these rules. The methods of are:
The constructor takes a single argument which is the template string.
Performs the template substitution, returning a new string. mapping is any dictionary-like object with keys that match the placeholders in the template. Alternatively, you can provide keyword arguments, where the keywords are the placeholders. When both mapping and kwds are given and there are duplicates, the placeholders from kwds take precedence.
Like , except that if placeholders are missing from mapping and kwds, instead of raising a exception, the original placeholder will appear in the resulting string intact. Also, unlike with , any other appearances of the $ will simply return $ instead of raising .
While other exceptions may still occur, this method is called “safe” because substitutions always tries to return a usable string instead of raising an exception. In another sense, may be anything other than safe, since it will silently ignore malformed templates containing dangling delimiters, unmatched braces, or placeholders that are not valid Python identifiers.
instances also provide one public data attribute:
This is the object passed to the constructor’s template argument. In general, you shouldn’t change it, but read-only access is not enforced.
Here is an example of how to use a Template:
>>> 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('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'>>> Template('$who likes $what').safe_substitute(d)'tim likes $what'
Advanced usage: you can derive subclasses of to customize the placeholder syntax, delimiter character, or the entire regular expression used to parse template strings. To do this, you can override these class attributes:
delimiter – This is the literal string describing a placeholder introducing delimiter. The default value is $. Note that this should not be a regular expression, as the implementation will call on this string as needed.
idpattern – This is the regular expression describing the pattern for non-braced placeholders (the braces will be added automatically as appropriate). The default value is the regular expression [_a-z][_a-z0-9]*.
flags – The regular expression flags that will be applied when compiling the regular expression used for recognizing substitutions. The default value isre.IGNORECASE. Note that re.VERBOSE will always be added to the flags, so custom idpatterns must follow conventions for verbose regular expressions.
New in version 3.2.
Alternatively, you can provide the entire regular expression pattern by overriding the class attribute pattern. If you do this, the value must be a regular expression object with four named capturing groups. The capturing groups correspond to the rules given above, along with the invalid placeholder rule:
转载地址:http://jmrua.baihongyu.com/