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

x = " \{ Hello \} {0} "
print(x.format(42))

gives me : Key Error: Hello\\

I want to print the output: {Hello} 42

This question is related to python string format string-formatting curly-braces

The answer is


Try this:

x = "{{ Hello }} {0}"


I am ridiculously late to this party. I am having success placing the brackets in the replacement element, like this:

print('{0} {1}'.format('{hello}', '{world}'))

which prints

{hello} {world}

Strictly speaking this is not what OP is asking, as s/he wants the braces in the format string, but this may help someone.


If you are going to be doing this a lot, it might be good to define a utility function that will let you use arbitrary brace substitutes instead, like

def custom_format(string, brackets, *args, **kwargs):
    if len(brackets) != 2:
        raise ValueError('Expected two brackets. Got {}.'.format(len(brackets)))
    padded = string.replace('{', '{{').replace('}', '}}')
    substituted = padded.replace(brackets[0], '{').replace(brackets[1], '}')
    formatted = substituted.format(*args, **kwargs)
    return formatted

>>> custom_format('{{[cmd]} process 1}', brackets='[]', cmd='firefox.exe')
'{{firefox.exe} process 1}'

Note that this will work either with brackets being a string of length 2 or an iterable of two strings (for multi-character delimiters).


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.


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.


Use escape sequences to escape the curly braces in the f-string. Ex:print(f'{a={1}}')


If you need to keep two curly braces in the string, you need 5 curly braces on each side of the variable.

>>> myvar = 'test'
>>> "{{{{{0}}}}}".format(myvar)
'{{test}}'

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}')

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'

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


I stumbled upon this problem when trying to print text, which I can copy paste into a Latex document. I extend on this answer and make use of named replacement fields:

Lets say you want to print out a product of mulitple variables with indices such as enter image description here, which in Latex would be $A_{ 0042 }*A_{ 3141 }*A_{ 2718 }*A_{ 0042 }$ The following code does the job with named fields so that for many indices it stays readable:

idx_mapping = {'i1':42, 'i2':3141, 'i3':2178 }
print('$A_{{ {i1:04d} }} * A_{{ {i2:04d} }} * A_{{ {i3:04d} }} * A_{{ {i1:04d} }}$'.format(**idx_mapping))

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


Try doing this:

x = " {{ Hello }} {0} "
print x.format(42)

If you need curly braces within a f-string template that can be formatted, you need to output a string containing two curly braces within a set of curly braces for the f-string:

css_template = f"{{tag}} {'{{'} margin: 0; padding: 0;{'}}'}"
for_p = css_template.format(tag="p")
# 'p { margin: 0; padding: 0;}'

You escape it by doubling the braces.

Eg:

x = "{{ Hello }} {0}"
print(x.format(42))

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}

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)  

You can use a "quote wall" to separate the formatted string part from the regular string part.

From:

print(f"{Hello} {42}")

to

print("{Hello}"f" {42}")

A clearer example would be

string = 10
print(f"{string} {word}")

Output:

NameError: name 'word' is not defined

Now, add the quote wall like so:

string = 10
print(f"{string}"" {word}")

Output:

10 {word}

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to format

Brackets.io: Is there a way to auto indent / format <html> Oracle SQL - DATE greater than statement What does this format means T00:00:00.000Z? How to format date in angularjs How do I change data-type of pandas data frame to string with a defined format? How to pad a string to a fixed length with spaces in Python? How to format current time using a yyyyMMddHHmmss format? java.util.Date format SSSSSS: if not microseconds what are the last 3 digits? Formatting a double to two decimal places How enable auto-format code for Intellij IDEA?

Examples related to string-formatting

JavaScript Chart.js - Custom data formatting to display on tooltip Format in kotlin string templates Converting Float to Dollars and Cents Chart.js - Formatting Y axis String.Format not work in TypeScript Use StringFormat to add a string to a WPF XAML binding How to format number of decimal places in wpf using style/template? How to left align a fixed width string? Convert Java Date to UTC String Format a Go string without printing?

Examples related to curly-braces

CURL to pass SSL certifcate and password What is the meaning of curly braces? When do we need curly braces around shell variables? How can I print literal curly-brace characters in a string and also use .format on it? Is it a bad practice to use an if-statement without curly braces? Go to Matching Brace in Visual Studio? Eclipse jump to closing brace