Python字符串模板
时间:2020-02-23 14:43:31 来源:igfitidea点击:
Python String Template类用于创建简单的模板字符串,以后可以其中替换字段以创建字符串对象。
我们也可以使用字符串format()函数创建一个字符串。
但是,format()函数提供了很多选项,并且在某些情况下,我们需要简单的替换功能,例如,国际化(i18n)。
在这些情况下,模板字符串非常有用且易于使用。
Python字符串模板
通过将模板字符串传递给其构造函数来创建Python字符串模板。
Python模板字符串支持基于$的替换。
模板类具有两个从模板创建字符串的功能。
replace(mapping,** kwds):从字典(如基于键的映射对象)或者从关键字参数执行替换。
如果映射和关键字参数都具有相同的键,则将引发TypeError。
错误消息看起来像TypeError:replace()
为关键字参数'aaa'获取了多个值。
如果未提供密钥,则将引发" KeyError"。safe_substitute(mapping,** kwds):行为与substitue()方法类似,除了找不到键时,它不会引发KeyError,并且在结果字符串中返回占位符。
Python模板字符串示例
让我们看一下python中模板字符串的简单示例。
from string import Template t = Template('$name is the $job of $company') s = t.substitute(name='Tim Cook', job='CEO', company='Apple Inc.') print(s) # dictionary as substitute argument d = {"name": "Tim Cook", "job": "CEO", "company": "Apple Inc."} s = t.substitute(**d) print(s)
输出:
Tim Cook is the CEO of Apple Inc. Tim Cook is the CEO of Apple Inc.
safe_substitute()示例
from string import Template t = Template('$name is the $job of $company') s = t.safe_substitute(name='Tim Cook', job='CEO') print(s)
输出:Tim Cook是$company的首席执行官。
打印模板字符串
模板对象具有返回模板字符串的" template"属性。
t = Template('$name is the $job of $company') print('Template String =', t.template)
输出:Template String = $name是$company的$job
转义$符号
我们可以使用$$来转义$符号并将其视为普通字符串的一部分。
t = Template('$$is called $name') s = t.substitute(name='Dollar') print(s)
输出:$被称为Dollar
${identifier}示例
${identifier}与$identifier相同。
当有效的标识符字符位于占位符之后但不是占位符的一部分时,则必须填写。
让我们用一个简单的例子来理解这一点。
t = Template('$noun adjective is ${noun}ing') s = t.substitute(noun='Test') print(s)