x = \" \\{ Hello \\} {0} \"
print(x.format(42))
gives me : Key Error: Hello\\\\
I want to print the output: {Hello} 42
If you want to only print one curly brace (for example {
) you can use {{
, and you can add more braces later in the string if you want.
For example:
>>> f'{{ there is a curly brace on the left. Oh, and 1 + 1 is {1 + 1}'
'{ there is a curly brace on the left. Oh, and 1 + 1 is 2'
You need to double the {{
and }}
:
>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '
Here's the relevant part of the Python documentation for format string syntax:
Format strings contain “replacement fields” surrounded by curly braces
{}
. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling:{{
and}}
.
You can do this by using raw string method by simply adding character 'r' without quotes before the string.
# to print '{I am inside braces}'
print(r'{I am inside braces}')
Try doing this:
x = " {{ Hello }} {0} "
print x.format(42)
Use escape sequences to escape the curly braces in the f-string. Ex:print(f'{a={1}}')
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.