私信  •  关注

Kristján Valur

Kristján Valur 最近创建的主题
Kristján Valur 最近回复了
4 年前
回复了 Kristján Valur 创建的主题 » python:无法格式化类似json的字符串[duplicate]

我最近遇到这个问题,因为我想将字符串注入预格式化的JSON。 我的解决方案是创建一个helper方法,如下所示:

def preformat(msg):
    """ allow {{key}} to be used for formatting in text
    that already uses curly braces.  First switch this into
    something else, replace curlies with double curlies, and then
    switch back to regular braces
    """
    msg = msg.replace('{{', '<<<').replace('}}', '>>>')
    msg = msg.replace('{', '{{').replace('}', '}}')
    msg = msg.replace('<<<', '{').replace('>>>', '}')
    return msg

然后,您可以执行以下操作:

formatted = preformat("""
    {
        "foo": "{{bar}}"
    }""").format(bar="gas")

如果性能不是问题,则完成任务。