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,主要作用就是字符串替换,主要应用场景是需要多语言支持的国际化。

关于$符号的使用该规则等,请参考: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 --

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值