2020年5月14日 / 65次阅读 / Last Modified 2020年5月14日
字符串
python的string模块,有一个叫做Template String的类,我们看代码的时候,有一些以$开头的字符串,就属于此类。
Template strings provide simpler string substitutions as described in PEP 292. A primary use case for template strings is for internationalization (i18n) since in that context, the simpler syntax and functionality makes it easier to translate than other built-in string formatting facilities in Python. As an example of a library built on template strings for i18n, see the flufl.i18n package.
Template Strings的源头是PEP 292,主要作用就是字符串替换,主要应用场景是需要多语言支持的国际化。
关于$符号的使用该规则等,请参考:https://docs.python.org/3/library/string.html#template-strings。$右面有无{}都可以,主要看是否会造成歧义。
下面的示例代码,也是官方的:
>>> 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'
substitute函数除了可以接受普通的key value paie之外,还可以直接使用dict对象,不需要unpakcing符号(**)。
下面是示例,是我自己的:
>>> from string import Template
>>> d
{'abc': 1, 'message': '12345', 'kkk': 12345}
>>> Template('$abc --> ${kkk} --> $message !').substitute(d)
'1 --> 12345 --> 12345 !'
>>> Template('$abc --> ${kkk} --> $message !').substitute(**d)
'1 --> 12345 --> 12345 !'
>>> Template('$abc --> ${kkk} --> $message !').substitute(kkk=12345, message='12345', abc=1)
'1 --> 12345 --> 12345 !'
这段代码,只要说明substitute函数可以使用的参数。
个人觉得Template String用处有限,学习主要也是为了阅读著名项目的代码。
-- EOF --
本文链接:https://www.pynote.net/archives/1916
©Copyright 麦新杰 Since 2019 Python笔记