Python的string模块中的Template类字符串模板用法
admin
2023-08-02 04:56:43
0

string.Template()
string.Template()内添加替换的字符, 使用\”$\”符号, 或 在字符串内, 使用\”${}\”; 调用时使用string.substitute(dict)函数.
可以通过继承\”string.Template\”, 覆盖变量delimiter(定界符)和idpattern(替换格式), 定制不同形式的模板.

代码:

# -*- coding: utf-8 -*- 

import string 
 
template_text = \'\'\'\'\' 
  Delimiter : %% 
  Replaced : %with_underscore 
  Ingored : %notunderscored 
\'\'\' 
 
d = {\'with_underscore\' : \'replaced\', 
   \'notunderscored\' : \'not replaced\'} 
 
class MyTemplate(string.Template): 
  delimiter = \'%\' 
  idpattern = \'[a-z]+_[a-z]+\' 
   
t = MyTemplate(template_text) 
print(\'Modified ID pattern: \') 
print(t.safe_substitute(d)) 

输出:

Modified ID pattern:  
 
  Delimiter : % 
  Replaced : replaced 
  Ingored : %notunderscored 

注意: 定界符(delimiter)为\”%\”, 替换模式(idpattern)必须包含下划线, 所以第2个没有进行替换.

正则替换

string.Template的pattern是一个正则表达式, 可以通过覆盖pattern属性, 定义新的正则表达式.
如: 使用新的定界符\”{{\”, 把{{var}}作为变量语法.

代码:

import string 
 
t = string.Template(\'$var\') 
print(t.pattern.pattern) 
 
class MyTemplate(string.Template): 
  delimiter = \'{{\' 
  pattern = r\'\'\'\'\' 
  \\{\\{(?: 
   (?P\\{\\{) |  # Escape sequence of two delimiters 
   (?P[_a-z][_a-z0-9]*)\\}\\}   |  # delimiter and a Python identifier 
   {(?P[_a-z][_a-z0-9]*)}\\}\\}  |  # delimiter and a braced identifier 
   (?P)       # Other ill-formed delimiter exprs 
  ) 
  \'\'\' 
   
t2 = MyTemplate(\'\'\'\'\' 
{{{{ 
{{var}} 
\'\'\') 
 
print(\'MATCHES: \', t2.pattern.findall(t2.template)) 
print(\'SUBSTITUTED: \', t2.safe_substitute(var=\'replacement\')) 

输出:

  \\$(?: 
   (?P\\$) |  # Escape sequence of two delimiters 
   (?P[_a-z][_a-z0-9]*)   |  # delimiter and a Python identifier 
   {(?P[_a-z][_a-z0-9]*)}  |  # delimiter and a braced identifier 
   (?P)       # Other ill-formed delimiter exprs 
  ) 
   
MATCHES: [(\'{{\', \'\', \'\', \'\'), (\'\', \'var\', \'\', \'\')] 
SUBSTITUTED:  
{{ 
replacement 

字符串模板的安全替换(safe_substitute)
字符串模板(sting.Template), 替换时, 使用substitute(), 未能提供模板所需的全部参数值时, 会发生异常.
如果使用safe_substitute(), 即安全替换, 则会替换存在的字典值, 保留未存在的替换符号.

代码:

import string 
 
values = {\'var\' : \'foo\'} 
 
t = string.Template(\'\'\'\'\'$var is here but $ missing is not provided! \'\'\') 
 
 
try: 
  print \'substitute() : \', t.substitute(values) 
except ValueError as err: 
  print \'Error:\', str(err) 
   
print \'safe_substitude() : \', t.safe_substitute(values) 

输出:

substitute() : Error: Invalid placeholder in string: line 1, col 18 
safe_substitude() : foo is here but $ missing is not provided!  

相关内容

热门资讯

Mobi、epub格式电子书如... 在wps里全局设置里有一个文件关联,打开,勾选电子书文件选项就可以了。
500 行 Python 代码... 语法分析器描述了一个句子的语法结构,用来帮助其他的应用进行推理。自然语言引入了很多意外的歧义,以我们...
定时清理删除C:\Progra... C:\Program Files (x86)下面很多scoped_dir开头的文件夹 写个批处理 定...
scoped_dir32_70... 一台虚拟机C盘总是莫名奇妙的空间用完,导致很多软件没法再运行。经过仔细检查发现是C:\Program...
65536是2的几次方 计算2... 65536是2的16次方:65536=2⁶ 65536是256的2次方:65536=256 6553...
小程序支付时提示:appid和... [Q]小程序支付时提示:appid和mch_id不匹配 [A]小程序和微信支付没有进行关联,访问“小...
pycparser 是一个用... `pycparser` 是一个用 Python 编写的 C 语言解析器。它可以用来解析 C 代码并构...
微信小程序使用slider实现... 众所周知哈,微信小程序里面的音频播放是没有进度条的,但最近有个项目呢,客户要求音频要有进度条控制,所...
Apache Doris 2.... 亲爱的社区小伙伴们,我们很高兴地向大家宣布,Apache Doris 2.0.0 版本已于...
python清除字符串里非数字... 本文实例讲述了python清除字符串里非数字字符的方法。分享给大家供大家参考。具体如下: impor...