How can I print literal curly-brace characters in python string and also use .format on it?

前端 未结 16 1638
面向向阳花
面向向阳花 2020-11-21 05:31
x = \" \\{ Hello \\} {0} \"
print(x.format(42))

gives me : Key Error: Hello\\\\

I want to print the output: {Hello} 42

16条回答
  •  情深已故
    2020-11-21 05:55

    I recently ran into this, because I wanted to inject strings into preformatted JSON. My solution was to create a helper method, like this:

    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
    

    You can then do something like:

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

    Gets the job done if performance is not an issue.

提交回复
热议问题