python字符串模板中的KeyError
2014-06-26 21:07
323 查看
由于新式的字符串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当成了变量,害我找了很久:
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当成了变量,害我找了很久:
相关文章推荐
- Python - 安全替换字符串模板(safe_substitute) 详细解释
- python中格式化字符串的方法(字符串模板的应用)
- python 字符串模板用法string.Template
- Python的string模块中的Template类字符串模板用法
- Learning Python 008 正则表达式-007 匹配的字符串模板中如果只有前面有字符串,而后面没有字符串时,这个匹配模板要怎 么写
- Python学习之模板字符串与模板注入
- Flask、Django模板网页显示python字符串的换行
- python字符串模板(Template)例子
- python学习笔记-使用re模板在字符串中查找所有单词
- Python - 字符串模板的安全替换(safe_substitute) 具体解释
- python —— 字符串模板和内建函数
- Python的string模块中的Template类字符串模板用法
- Python 字符串模板
- Python - 字符串模板的安全替换(safe_substitute) 详解
- Python的string模块中的Template类字符串模板用法
- 字符串模板(Python)
- Python的字符串模板(Template)使用操作实例讲解
- [python]一行搞定字符串排序
- Python Cookbook 第二版 汉化版 [Recipe 1.7] 以单词或字符为单位对字符串进行反序排列
- Python Cookbook 第二版 汉化版 [Recipe 1.6] 字符串的组合