python string模块template_Template Strings
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,主要作用就是字符串替換,主要應用場景是需要多語言支持的國際化。
關于$符號的使用該規(guī)則等,請參考: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函數(shù)除了可以接受普通的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函數(shù)可以使用的參數(shù)。
個人覺得Template String用處有限,學習主要也是為了閱讀著名項目的代碼。
-- EOF --
總結
以上是生活随笔為你收集整理的python string模块template_Template Strings的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java中string字符串的值_Jav
- 下一篇: java文件读取异常_关于Java:从文