x = \" \\{ Hello \\} {0} \"
print(x.format(42))
gives me : Key Error: Hello\\\\
I want to print the output: {Hello} 42
You escape it by doubling the braces.
Eg:
x = "{{ Hello }} {0}"
print(x.format(42))
Although not any better, just for the reference, you can also do this:
>>> x = '{}Hello{} {}'
>>> print x.format('{','}',42)
{Hello} 42
It can be useful for example when someone wants to print {argument}
. It is maybe more readable than '{{{}}}'.format('argument')
Note that you omit argument positions (e.g. {}
instead of {0}
) after Python 2.7
Python 3.6+ (2017)
In the recent versions of Python one would use f-strings (see also PEP498).
With f-strings one should use double {{
or }}
n = 42
print(f" {{Hello}} {n} ")
produces the desired
{Hello} 42
If you need to resolve an expression in the brackets instead of using literal text you'll need three sets of brackets:
hello = "HELLO"
print(f"{{{hello.lower()}}}")
produces
{hello}
When you're just trying to interpolate code strings I'd suggest using jinja2 which is a full-featured template engine for Python, ie:
from jinja2 import Template
foo = Template('''
#include <stdio.h>
void main() {
printf("hello universe number {{number}}");
}
''')
for i in range(2):
print(foo.render(number=i))
So you won't be enforced to duplicate curly braces as the whole bunch of other answers suggest
Reason is , {}
is the syntax of .format()
so in your case .format()
doesn't recognize {Hello}
so it threw an error.
you can override it by using double curly braces {{}},
x = " {{ Hello }} {0} "
or
try %s
for text formatting,
x = " { Hello } %s"
print x%(42)
The OP wrote this comment:
I was trying to format a small JSON for some purposes, like this:
'{"all": false, "selected": "{}"}'.format(data)
to get something like{"all": false, "selected": "1,2"}
It's pretty common that the "escaping braces" issue comes up when dealing with JSON.
I suggest doing this:
import json
data = "1,2"
mydict = {"all": "false", "selected": data}
json.dumps(mydict)
It's cleaner than the alternative, which is:
'{{"all": false, "selected": "{}"}}'.format(data)
Using the json
library is definitely preferable when the JSON string gets more complicated than the example.