python $variable substitute in string using string Template module

简介:
Template(string)用于构造一个实例, 这个实例中的$var 可以被Template的substitute()或safe_substitute()方法来替换.
用法举例 :
>>> 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 "<stdin>", line 1, in <module>
  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 "<stdin>", line 1, in <module>
  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'


[参考]

6.1.4. Template strings

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**kwds)

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.

safe_substitute( mapping**kwds)

Like substitute(), except that if placeholders are missing from mapping and kwds, 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 $ will simply return $ 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 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 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 is $. 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]*.

  • 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:

  • 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.
目录
相关文章
|
6月前
|
存储 Java 索引
Python String详解!
本文详细介绍了Python中的字符串数据类型,包括其创建、访问、切片、反转及格式化等操作。文章涵盖字符串的基本概念、各种操作方法以及常用内置函数。通过多个示例代码展示了如何使用单引号、双引号和三重引号创建字符串,如何通过索引和切片访问与修改字符串内容,以及如何利用格式化方法处理字符串。此外,还介绍了字符串的不可变性及其在实际应用中的重要性。通过本文的学习,读者可以全面掌握Python字符串的使用技巧。
141 4
|
6月前
|
Python
python Module使用
【10月更文挑战第14天】 python Module使用
157 35
|
6月前
|
Linux Python
【Azure Function】Python Function部署到Azure后报错No module named '_cffi_backend'
ERROR: Error: No module named '_cffi_backend', Cannot find module. Please check the requirements.txt file for the missing module.
150 2
|
6月前
|
Go C++ Python
Python Tricks: String Conversion(Every Class Needs a ___repr__)
Python Tricks: String Conversion(Every Class Needs a ___repr__)
46 5
|
6月前
|
安全 JavaScript 前端开发
Python Tricks: A Shocking Truth About String Formatting(二)
Python Tricks: A Shocking Truth About String Formatting(二)
46 2
|
6月前
|
Python
Python Tricks: A Shocking Truth About String Formatting(一)
Python Tricks: A Shocking Truth About String Formatting(一)
69 0
|
8月前
|
JavaScript 前端开发 Python
成功解决:Can‘t find Python executable “python“, you can set the PYTHON env variable.
这篇文章分享了作者在运行前端Vue项目时遇到的关于Python执行环境的问题和解决方法。问题是由于找不到Python可执行文件导致的编译错误,解决方法包括安装编译环境、卸载并重新安装出现问题的`node-sass`包,并重新执行`npm install`和`npm run dev`。
成功解决:Can‘t find Python executable “python“, you can set the PYTHON env variable.
|
8月前
|
SQL JSON 测试技术
Python中的f-string
Python中的f-string
250 2
|
8月前
|
存储 Serverless 数据处理
Python - len(string)函数
通过上述介绍和示例,我们可以清楚地看到,在Python中,`len()`函数是处理字符串以及其他可迭代对象长度的重要工具。它简单、易用,但在实际应用中却非常强大,无论是在基础编程还是在复杂的数据处理中,`len()`函数都扮演着不可或缺的角色。
155 10
|
8月前
|
数据处理 Python
【Python】解决tqdm ‘module‘ object is not callable
在使用tqdm库时遇到的“'module' object is not callable”错误,并给出了正确的导入方式以及一些使用tqdm的常见示例。
243 1

热门文章

最新文章

下一篇
oss创建bucket