现在的位置: 首页 > 综合 > 正文

python字符串模板中的KeyError

2018年05月08日 ⁄ 综合 ⁄ 共 962字 ⁄ 字号 评论关闭

由于新式的字符串Template对象的引进使得string 模块又重新活了过来,Template对象有两个方法:substitute()和safe_substitute()。

python中string的Template类似C语言中printf中的<格式化字符串>,使用“${*}”声明变量(类似C语言中的"%*");紧跟substitute则类似printf的<变量参数表>,必须一一对应,数量必须严格匹配。

当缺少参数(key)时,substitute会报一KeyError的异常出来;而safe_substitute则会直接原封不动的把字符串显示出来。

>>> from string import Template

>>> s =Template('There are ${howmany} ${lang} Quotation Symbols')  #声明模板

>>> print s.substitute(lang='Python', howmany=3)  #给变量传参

>>>There are 3 Python Quotation Symbols#正常输出

>>>

>>> print s.substitute(lang='Python')  #缺少key:${howmany}

>>> Traceback (most recent call last):

File "<stdin>", line 1, in ?
File "/usr/local/lib/python2.4/string.py", line 172, in substitute
return self.pattern.sub(convert, self.template)
File "/usr/local/lib/python2.4/string.py", line 162, in convert val = mapping[named]
KeyError:
'howmany' #substitute异常报错

>>>
>>> print s.safe_substitute(lang='Python')

There are${howmany} Python Quotation Symbols #safe_substitute异常报错,缺少参数


比较矬的是,我在sql语句的--注释中出现了“${YYYYMMDD}”,结果被Template当成了变量,害我找了很久:


抱歉!评论已关闭.