日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python string模块template_Template Strings

發布時間:2025/3/20 python 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 --

總結

以上是生活随笔為你收集整理的python string模块template_Template Strings的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。