2427

Non-working example:

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

Desired output:

 {Hello} 42 
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Schitti
  • 25,489
  • 8
  • 24
  • 21
  • 1
    See also: http://stackoverflow.com/questions/35574349 – dreftymac Dec 06 '16 at 05:11
  • 22
    For those who want to avoid doubling braces (`{{ }}`), use [`string.Template`](https://docs.python.org/3/library/string.html#template-strings). There you substitute identifiers of the form `$foo` (handy for generating LaTeX code). – 0 _ Jan 11 '18 at 05:51
  • 2
    For those who want to avoid doubling braces, and who are not averse to adding another dependency to their Python projects, there is also [Jinja2](https://stackoverflow.com/tags/jinja2/info) which definitively solves this problem, by allowing user-defined custom placeholder delimiter syntax. – dreftymac Jan 15 '20 at 20:07

23 Answers23

3245

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 }}.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 380
    So if you want to print "{42}", you'd use `"{{{0}}}".format(42)` ! – hughes Jul 24 '13 at 20:21
  • 19
    What about if you want a single curly brace? `"{ something { } {value}".format(42)` doesn't work. – AJP Oct 02 '13 at 10:10
  • 27
    "{{".format() and "}}".format() print single curly braces. In your example: print "{{ something {{ }} {0}".format(42) will print "{ something { } 42". – Mark Visser Oct 18 '13 at 21:19
  • 3
    What does the `{0}` mean? – CodyBugstein Feb 21 '14 at 01:27
  • 9
    @Imray: `{0}` refers to the first argument to `.format()`. You can print more than one value like `{0} {1} {2}` as long as you give the same number of arguments to `.format()`. See http://docs.python.org/library/string.html#format-examples for extensive examples. – Greg Hewgill Feb 21 '14 at 01:30
  • 1
    The Sen of Python: Beautiful is better than ugly. The beauty of Python @Mark Visser – Josue Montano Jun 07 '15 at 15:30
  • Thanks @GregHewgill after 5 years working with format I never had to escape curly braces I was getting mad, thanks for the answer – Angel Velásquez Jan 03 '16 at 16:47
  • How do you get {} inside real {} though ? Like for padding ? – Bite code Mar 25 '16 at 15:59
  • 1
    Sooooo... what do you do if you want to print an empty dictionary in one line without using `dict()` during a full moon in October? :P – Mateen Ulhaq Oct 16 '18 at 21:52
  • 1
    @hughes At that point, it might be more clear to do `"{" + str(42) + "}"` – Trenton Dec 05 '18 at 21:49
  • How do I print `{{}}` , I want to construct a string contain `{{}}` . This `f'/test/forecast/{VERSION}/{{{ execution_date.strftime("%Y-%m-%d") }}}/r={remainder}'` would throw error . I need `{{ execution_date.strftime("%Y-%m-%d") }}` in this string, which is used in airflow dag mixed jinja template language and python code . – Mithril Aug 28 '19 at 09:28
  • 2
    @Mithril: You still need to *double* each curly brace. So you might need `f'/blah/blah/{{{{ strftime(...) }}}/blah'` or something. – Greg Hewgill Aug 28 '19 at 10:06
  • With the dawn of `f` strings in Python 3.6 and the printing of "{42}", you'd now do something like `f"{{42}}"`. See the answer from @divenex for more details. – Gwi7d31 Nov 20 '20 at 18:24
  • Does anyone know **why** it's `{{` instead of `\{`? – MarcellPerger Jul 10 '23 at 16:56
242

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}
Bryan Bryce
  • 1,310
  • 1
  • 16
  • 29
divenex
  • 15,176
  • 9
  • 55
  • 55
  • 2
    From `my_greet = "HELLO"` you can get `{hello}` as output, using just 2 sets of brackets, with `print(f"{ {my_greet.lower()} }")`. Just leave a space between brackets. – yrnr Jul 20 '20 at 07:07
  • 1
    This should now be the accepted answer if you are using Python3.6+ in the times of the rona. – Gwi7d31 Nov 20 '20 at 18:27
  • @Gwi7d31 No, f-strings are not a replacement for `str.format()`. For example, [this answer I wrote](/a/67449534/4518341) is not possible with f-strings since the template is coming from input, not source code. – wjandrea May 20 '21 at 18:20
  • 1
    @wjandrea your link really doesn't pertain to the OPs question. The OP wants to keep curly-braces while you are removing them in your linked answer via .format() and your dictionary unpacking method. If you want to preserve {} in Python 3.6+ and you want to insert a value into a string, `this is the way`. That's the question at hand. I also never said f-strings are a replacement for .format(). You said that. – Gwi7d31 May 26 '21 at 03:06
  • @Gwi What I'm saying is, this question is about `str.format()`, not f-strings, and they're not mutually compatible. – wjandrea May 26 '21 at 03:18
  • So basically just keep adding curly brackets until it works. Got it. – Patrick Sep 18 '21 at 04:52
115

You escape it by doubling the braces.

Eg:

x = "{{ Hello }} {0}"
print(x.format(42))
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Kamil Kisiel
  • 19,723
  • 11
  • 46
  • 56
72

You want to format a string with the character { or }

You just have to double them.

format { with f'{{' and }with f'}}'

So :

name = "bob"
print(f'Hello {name} ! I want to print }} and {{ or {{ }}')

Output :

Hello bob ! I want to print } and { or { }

OR for the exact example :

number = 42
print(f'{{Hello}} {number}')

Will print :

{Hello} 42

Finally :

number = 42
string = "bob"
print(f'{{Hello}} {{{number}}} {number} {{{string}}} {string} ')

{Hello} {42} 42 {bob} bob

Nicoolasens
  • 2,871
  • 17
  • 22
67

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.

Nick T
  • 25,754
  • 12
  • 83
  • 121
twasbrillig
  • 17,084
  • 9
  • 43
  • 67
  • 1
    Amen! It might seem like more work, but using libraries to do what libraries are supposed to do versus cutting corners...makes for better things. – Kaolin Fire Apr 10 '18 at 19:12
  • 1
    But the order of the keys in a Python object isn't guaranteed... Still, the JSON library is guaranteed to serialise in a JSON way. – wizzwizz4 Jun 30 '18 at 08:34
  • 2
    wizzwizz4: Good point. From Python 3.6 onward, dictionaries are insertion ordered, so it wouldn't be an issue. Versions of Python between 2.7 and 3.5 can use OrderedDict from the collections library. – twasbrillig Jul 01 '18 at 18:47
  • 1
    The alternative is also terribly wrong if, e.g., `data = 'foo"'`, because the `"` in the value of `data` won't be properly escaped. – chepner Dec 31 '20 at 21:42
  • 1
    If you're dealing with JSON, this answer is for you. It wins in terms of readability and maintainability - imagine dealing with complex JSON structures and a lot of double braces in it – panK Oct 16 '21 at 21:00
39

Try this:

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

pajton
  • 15,828
  • 8
  • 54
  • 65
31

Try doing this:

x = " {{ Hello }} {0} "
print x.format(42)
DNR
  • 956
  • 6
  • 10
16

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

George Aprilis
  • 1,140
  • 1
  • 9
  • 23
12
key = "FOOBAR"
print(f"hello {{{key}}}")

outputs

hello {FOOBAR}

In case someone wanted to print something inside curly brackets using fstrings.

defiant
  • 3,161
  • 11
  • 41
  • 65
10

f-strings (python 3)

You can avoid having to double the curly brackets by using f-strings ONLY for the parts of the string where you want the f-magic to apply, and using regular (dumb) strings for everything that is literal and might contain 'unsafe' special characters. Let python do the string joining for you simply by stacking multiple strings together.

number = 42
print(" { Hello }"  
f" {number} " 
"{ thanks for all the fish }")

### OUTPUT:
{ Hello } 42 { thanks for all the fish }

NOTE: Line breaks between the strings are NOT required. I have only added them for readability. You could as well write the code above as shown below:

⚠️ WARNING: This might hurt your eyes or make you dizzy!

print("{Hello}"f"{number}""{thanks for all the fish}")
ccpizza
  • 28,968
  • 18
  • 162
  • 169
  • 1
    Implicit string concatenation is discouraged. Guido copied it from C but the reason why it's needed there doesn't really apply to Python. - https://groups.google.com/g/python-ideas/c/jP1YtlyJqxs?pli=1 – ankit Aug 05 '22 at 14:12
9

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}}'
Richard
  • 2,396
  • 23
  • 23
  • 3
    For those using f-strings, use 4 curly braces on either side instead of 5 – TerryA Sep 19 '19 at 07:11
  • 1
    @TerryA there isn't a difference in brace behavior between .format and f-strings. The code `a = 1; print('{{{{{a}}}}}'.format(a=a))` produces the same results as `a = 1; print(f'{{{{{a}}}}}')`. – Kerrick Staley Jun 10 '21 at 19:07
6

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).

tvt173
  • 1,746
  • 19
  • 17
  • Thought about that also. Of course, that will work too and the algorithm is simpler. But, imagine you have a lot of text like this, and you just want to parameterize it here and there. Everytime you create an input string you wouldn't want to replace all those braces manually. You would just want to 'drop in' your parameterizations here and there. In this case, I think this method is both easier to think about and accomplish from a user perspective. I was inspired by linux's 'sed' command which has similar capabilities to arbitrarily choose your delimiter based on what is convenient. – tvt173 Dec 01 '16 at 18:53
  • In short, I'd rather have the utility function be a little more complex than have it be a pain in the @$$ to use everytime. Please let me know if I misunderstood your proposition. – tvt173 Dec 01 '16 at 18:56
  • I've gone ahead and added a short demo to my public.lab space https://github.com/dreftymac/public.lab/blob/master/topic/python/string.format/readme.md – dreftymac Dec 01 '16 at 20:56
5

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.

Kristján Valur
  • 137
  • 1
  • 2
  • Simple AND elegant to integrate into existing code with little modification required. Thanks! – Column01 May 12 '20 at 16:22
  • of course, assuming your text never contained any `<<<` and `>>>` to begin with, otherwise those would get overwritten. best to use escape strategies for reliability! – axolotl Aug 25 '21 at 15:39
  • What escape strategy do you suggest? Anyway, you know your templated text and can amend the magic strings in case you worry about clashes. – Kristján Valur Aug 27 '21 at 12:38
  • This approach is highly flexible and is even more workable by just borrowing a convention from Perl. Simply 1) choose a sequence of characters that you know will not appear in the target text (eg `QQX`); 2) use that sequence as your variable placeholders `QQX`; 3) do a regex replacement to convert your placeholders to the expected format (eg) `r'QQ<([^>]+)>','{$1}'`. **See also:** [perl quotelike operator](https://stackoverflow.com/questions/16371829) – dreftymac Mar 28 '23 at 23:17
3

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)  
Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118
  • This is so simple. I always forget about percent-style formatting. It is still valid in all Python versions, and it makes my quick and dirty test with a JSON string that needs number formatting so much cleaner. – Matthew May 12 '23 at 16:52
3

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.

Puddles
  • 122
  • 7
0

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))
v.tralala
  • 1,444
  • 3
  • 18
  • 39
0

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}
Red
  • 26,798
  • 7
  • 36
  • 58
  • 1
    This looks more like concatenation, but nice thinking – Delrius Euphoria Jun 14 '21 at 06:49
  • 1
    I would advise against this - it's using a feature of the language which is itself controversial and described by Guido as a mistake (implicit string concatenation) and using it in a way that is, itself, unusual and therefore confusing. Many people who hit this are going to struggle to work out what is going on. It's essentially just going f"{string}" + " {word}" which is simple and straightforward but doing so in a more confusing way. It reminds me of the fake 'getting the single element of a set operator' ,= as used in elem ,= {'single_element'} which works but just causes confusion! – Andrew McLeod Jun 25 '21 at 14:31
0

I used a double {{ }} to prevent fstring value injection,

for example, heres my Postgres UPDATE statement to update a integer array column that takes expression of {} to capture the array, ie:

ports = '{100,200,300}'

with fstrings its,

ports = [1,2,3]

query = f"""
   UPDATE table SET ports = '{{{ports}}}' WHERE id = 1
"""

the actual query statement will be,

UPDATE table SET ports = '{1,2,3}'

which is a valid postgres satement

perfecto25
  • 772
  • 9
  • 13
0

If you want to print just one side of the curly brace:

a=3
print(f'{"{"}{a}')
>>> {3
DalyaG
  • 2,979
  • 2
  • 16
  • 19
-1

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'
Luis Cabrera Benito
  • 1,558
  • 13
  • 21
-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

BPL
  • 9,632
  • 9
  • 59
  • 117
  • 1
    I agree that avoiding duplicating curly braces is a good thing — but rather than reach for jinja2 I'd just use python's own `string.Template` class, which is plenty powerful enough for this kind of thing. – gimboland Aug 03 '21 at 16:06
-2

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;}'
RunOrVeith
  • 4,487
  • 4
  • 32
  • 50
  • 1
    this question was not about f-strings, and IMO combining f-strings and format in this way makes for pretty unreadable code – avigil Feb 25 '21 at 17:07
  • It is the first result that comes up when you google how to put curly braces in python f-strings though, and yes I agree it's not pretty but sometimes you just need it. – RunOrVeith Feb 26 '21 at 08:28
-3

Or just parametrize the bracket itself? Probably very verbose.

x = '{open_bracket}42{close_bracket}'.format(open_bracket='{', close_bracket='}') 
print(x)
# {42}
Mortz
  • 4,654
  • 1
  • 19
  • 35