問題描述
有沒有辦法使用python string.format,當(dāng)索引丟失時不會拋出異常,而是插入一個空字符串.
Is there a way to use python string.format such that no exception is thrown when an index is missing, instead an empty string is inserted.
result = "i am an {error} example string {error2}".format(hello=2,error2="success")
這里,結(jié)果應(yīng)該是:
"i am an example string success"
現(xiàn)在,python 拋出一個 keyerror 并停止格式化.是否可以改變這種行為?
Right now, python throws a keyerror and stops formatting. Is it possible to change this behavior ?
謝謝
存在 Template.safe_substitute (即使保留模式完整而不是插入空字符串),但 string.format 不能有類似的東西
There exists Template.safe_substitute (even that leaves the pattern intact instead of inserting an empty string) , but couldn't something similar for string.format
所需的行為類似于 php 中的字符串替換.
The desired behavior would be similar to string substitution in php.
class Formatter(string.Formatter):
def get_value(self,key,args,kwargs):
try:
if hasattr(key,"__mod__"):
return args[key]
else:
return kwargs[key]
except:
return ""
這似乎提供了所需的行為.
This seems to provide the desired behavior.
推薦答案
str.format()
不需要映射對象.試試這個:
str.format()
doesn't expect a mapping object. Try this:
from collections import defaultdict
d = defaultdict(str)
d['error2'] = "success"
s = "i am an {0[error]} example string {0[error2]}"
print s.format(d)
您使用返回"的 str()
工廠創(chuàng)建一個 defaultdict.然后你為 defaultdict 創(chuàng)建一個鍵.在格式字符串中,您訪問傳遞的第一個對象的鍵.這樣做的好處是允許您傳遞其他鍵和值,只要您的 defaultdict 是 format()
的第一個參數(shù).
You make a defaultdict with a str()
factory that returns "". Then you make one key for the defaultdict. In the format string, you access keys of the first object passed. This has the advantage of allowing you to pass other keys and values, as long as your defaultdict is the first argument to format()
.
另外,請參閱 http://bugs.python.org/issue6081
這篇關(guān)于python字符串格式抑制/靜默keyerror/indexerror的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!