替换文本中的$占位符 Template.substitute、 Template.safe_substitute

来源:互联网 发布:儿童编程网站 编辑:程序博客网 时间:2024/05/17 05:04

要替换文本中的特定占位符怎么办?

用Template类的substitute方法,Template是string类的一个子类。

怎么标定占位符呢?

用特殊字符$

下文是对《python v.2.7.1 documentation》的引用,具体讲了:

  • Template类的substitute和safe_substitute方法;

  • 根据需要改变占位符的识别字符$的方法;

Templates provide simpler string substitutions as described in PEP 292. Instead of the normal %-based substitutions, Templates support $-based substitutions, using the following rules:

  • $$ is an escape; it is replaced with a single$.
  • $identifier names a substitution placeholder matching a mapping key of “identifier”. By default, “identifier” must spell a Python identifier. The first non-identifier character after the $ character terminates this placeholder specification.
  • ${identifier} is equivalent to $identifier. It is required when valid identifier characters follow the placeholder but are not part of the placeholder, such as "${noun}ification".

Any other appearance of $ in the string will result in a ValueError being raised.

The string module provides a Template class that implements these rules. The methods of Template are:

class string**.Template***(template)*

The constructor takes a single argument which is the template string.

substitute(mapping[, **kws])

Fuction: 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 kws are given and there are duplicates, the placeholders from kws take precedence.

safe_substitute(mapping[, **kws])

Fuction: Like substitute(), except that if placeholders are missing from mapping and kws, instead of raising a KeyError exception, the original placeholder will appear in the resulting string intact. Also, unlike with substitute(), any other appearances of the willsimplyreturn instead of raising ValueError.

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:

safe_substitute() 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.

Template instances also provide one public data attribute:

template

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 10>>> 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 Template 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 $. Note that this should not be a regular expression, as the implementation will call re.escape() 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]*.

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:

  • escaped – This group matches the escape sequence, e.g. $$, in the default pattern.
  • named – This group matches the unbraced placeholder name; it should not include the delimiter in capturing group.
  • braced – This group matches the brace enclosed placeholder name; it should not include either the delimiter or braces in the capturing group.
  • invalid – This group matches any other delimiter pattern (usually a single delimiter), and it should appear last in the regular expression.
0 0
原创粉丝点击