本文共 3513 字,大约阅读时间需要 11 分钟。
python 字符串模板
Python String Template class is used to create a simple template string, where fields can be replaced later on to create a string object. We can use function to create a string too. However, format() function provides a lot of options and in some situations, we want the simple replacement features, for example, Internationalization (i18n). In these cases, template string is useful and easy to use.
Python String Template类用于创建简单的模板字符串,以后可以在其中替换字段以创建字符串对象。 我们也可以使用函数创建一个字符串。 但是,format()函数提供了很多选项,并且在某些情况下,我们需要简单的替换功能,例如,国际化(i18n)。 在这些情况下,模板字符串非常有用且易于使用。
Template is created by passing template string to its constructor. Python template strings support $-based substitutions.
通过将模板字符串传递到其构造函数来创建模板。 Python模板字符串支持基于$的替换。
Template class has two functions to create a string from the template.
模板类具有两个从模板创建字符串的功能。
TypeError: substitute() got multiple values for keyword argument 'aaa'
. If the key is not provided, then KeyError
will be raised. replace(mapping,** kwds) :从像基于键的映射对象之类的或从关键字参数中执行替换。 如果映射参数和关键字参数都具有相同的键,则将引发TypeError。 错误消息将看起来像TypeError: substitute() got multiple values for keyword argument 'aaa'
。 如果未提供密钥,则将引发KeyError
。 Let’s look at simple example of template string in python.
让我们看一下python中模板字符串的简单示例。
from string import Templatet = Template('$name is the $job of $company')s = t.substitute(name='Tim Cook', job='CEO', company='Apple Inc.')print(s)# dictionary as substitute argumentd = {"name": "Tim Cook", "job": "CEO", "company": "Apple Inc."}s = t.substitute(**d)print(s)
Output:
输出:
Tim Cook is the CEO of Apple Inc.Tim Cook is the CEO of Apple Inc.
from string import Templatet = Template('$name is the $job of $company')s = t.safe_substitute(name='Tim Cook', job='CEO')print(s)
Output: Tim Cook is the CEO of $company
输出: Tim Cook is the CEO of $company
Template object has “template” attribute that returns the template string.
模板对象具有返回模板字符串的“ template”属性。
t = Template('$name is the $job of $company')print('Template String =', t.template)
Output: Template String = $name is the $job of $company
输出: Template String = $name is the $job of $company
We can use $$ to escape $ sign and treat it as part of normal string.
我们可以使用$$来转义$符号并将其视为普通字符串的一部分。
t = Template('$$ is called $name')s = t.substitute(name='Dollar')print(s)
Output: $ is called Dollar
输出: $ is called Dollar
${identifier} is same as $identifier. It’s required when valid identifier characters follow the placeholder but are not part of the placeholder. Let’s understand this with a simple example.
$ {identifier}与$ identifier相同。 当有效的标识符字符位于占位符之后但不是占位符的一部分时,这是必需的。 让我们用一个简单的例子来理解这一点。
t = Template('$noun adjective is ${noun}ing')s = t.substitute(noun='Test')print(s)
Output: Test adjective is Testing
输出: Test adjective is Testing
翻译自:
python 字符串模板
转载地址:http://iamzd.baihongyu.com/