python string.format, keep unused/overused keys [duplicate]

主宰稳场 提交于 2019-12-10 23:13:10

问题


I have template strings with named arguments (for ex. msg = "{a} {b} {c}") and series of functions returning results of some statistical calculations in dictionaries. I want to use these dictionaries to fill templates. However, there is a problem. The exact number of the arguments in the template is not as same as in the dictionary; thus, I can not use simple msg.format(**result). Is there a way to overcome this problem, keeping unused format-blocks for further use?

This is what I have:

msg.format(a=1,b=2) -> KeyError: 'c'

This is what I want:

msg.format(a=1,b=2) -> "1 2 {c}"

来源:https://stackoverflow.com/questions/59035110/python-string-format-keep-unused-overused-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!