substitute() : Error: Invalid placeholder in string: line 1, col 18 safe_substitude() : foo is here but $ missing is not provided!
输出: substitute() : Error: Invalid placeholder in string: line 1, col 18 safe_substitude() : foo is here but $ missing is not provided! 1. 2.
s1 ="我在用${ code }${num}开发项目"s = Template(s1)print(s.safe_substitute(code='Python',num=3))print(s.substitute(code='Python',num=3)) 运行上面的代码,从结果中可以看出safe_substitute原样输出了变量,没有报错。substitute方法则报错 # safe_substitute输出结果# 我在用 ${ code } 3 开发...
importstringvalues={'var':'foo'}t=string.Template("$var is here but $missing is not provided")try:print('substitute() :',t.substitute(values))exceptKeyErroraserr:print('ERROR:',str(err))print('safe_substitute():',t.safe_substitute(values)) 输出: ERROR: 'missing' safe_substitute(): fo...
>>> t.safe_substitute(d) 'Return the unladen swallow to $owner.' Template 的子类可以自定义分隔符。例如,以下是某个照片浏览器的批量重命名功能,采用了百分号作为日期、照片序号和照片格式的占位符: import time, os.path from string import Template ...
Template的实现方式是首先通过Template初始化一个字符串。这些字符串中包含了一个个key。通过调用substitute或safe_subsititute,将key值与方法中传递过来的参数对应上,从而实现在指定的位置导入字符串。这种方式的好处是不需要担心参数不一致引发异常,如: fromstringimportTemplate ...
这和 Python 内置的 string 标准库中 Template 类的 substitute()模板方法一样存在着同样的安全隐患,所以使用 safe_substitute()来替代是一样的道理。如我们现在将之前的一些配置信息写入 config.yaml 文件中:mysql:host: "127.0.0.1" port: 3306 user: "root" password: "123456" database: "test"...
template_str=string.Template(s)print(template_str.safe_substitute(values)) 因为字典没有对应的值进行替换,所以会保留原始的字符串数据。效果如下: 高级模板 上面的模板使用方法是string库默认提供的规则体系。其实,我们还可以自定义模板的使用匹配方法,具体代码如下: ...
File "/usr/lib/python2.7/string.py", line 176, in substitute return self.pattern.sub(convert, self.template) File "/usr/lib/python2.7/string.py", line 166, in convert val = mapping[named] KeyError: 'girlfriend' >>> print s.safe_substitute(name='xpleaf') ...
这时就可以改用safe_substitute方法,该方法只替换参数与模板中能匹配的部分占位符,其余占位符将被忽略,不会引发错误。 操作流程 步骤1:导入Template类。 步骤2:定义字符串模板。 步骤3:调用safe_substitute方法替换占位符。 上述调用中,只对名为“who”的占位符进行替换,但名为“football”的占位符没有被替换。