x = \" \\{ Hello \\} {0} \"
print(x.format(42))
gives me : Key Error: Hello\\\\
I want to print the output: {Hello} 42>
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.