使用python str.format()在字符串中仅用名称替换一些参数

时间:2014-12-19 15:56:43

标签: python string replace format

我试图使用pythons str.format(dict)替换str中的一些命名参数 - 但不是全部。我想在我的代码中稍后替换剩余的命名参数:

strDict = {'title':'This is the title.', 'msg':'This is the message'}
str2 = '{title}\n{msg}\n{furtherMsg}'.format(**strDict)
strDict2 = {'furtherMsg':'some more text'}
outStr = str2.format(**strDict2)

但是,我得到了一个KeyError:'在str2 = ...行中的FurtherMsg ... 有没有办法只用str.format()?

替换字符串中的一些命名参数

我知道,在上面的简单示例中,我可以在结尾处使用格式和组合字典,但这不是我原始问题中的一个选项。

我正在使用Python 2.7。

编辑:

我尝试了martijn-pieters提出的问题的解决方案,但它不起作用:

class D(dict):
    def __missing__(self, k):
        return '{'+k+'}'
strDict = D({'title':'This is the title', 'msg':'This is the message.'})
str2 = '{title}\n{msg}\n{furtherMsg}'.format(**strDict)

仍然给我一个KeyError:' FurtherMsg',而

strDict['furtherMsg']

返回

'furtherMsg'

我也试过

class D(dict):
        def __missing__(self, k):
            return '{{'+k+'}}'

但这也不起作用。

0 个答案:

没有答案