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

Answer from Greg Hewgill on Stack Overflow
🌐
Manifoldapp
cuny.manifoldapp.org › read › how-to-code-in-python-3 › section › 07f9968a-8f75-4d3c-8573-2e9282745e9e
How To Use String Formatters | How To Code in Python 3 | Manifold @CUNY
In this second example, we concatenated the string "open source" with the larger string, replacing the curly braces in the original string. Formatters in Python allow you to use curly braces as placeholders for values that you’ll pass through with the str.format() method.
🌐
Runestone Academy
runestone.academy › ns › books › published › fopp › Sequences › IndexOperatorWorkingwiththeCharactersofaString.html
6.3. Index Operator: Working with the Characters of a String — Foundations of Python Programming
The indexing operator (Python uses square brackets to enclose the index) selects a single character from a string. The characters are accessed by their position or index value. For example, in the string shown below, the 14 characters are indexed left to right from postion 0 to position 13.
Discussions

python - How do I escape curly-brace ({}) characters characters in a string while using .format? - Stack Overflow
From my_greet = "HELLO" you can ... between brackets. 2020-07-20T07:07:10.953Z+00:00 ... This should now be the accepted answer if you are using Python3.6+ in the times of the rona. 2020-11-20T18:27:33.007Z+00:00 ... @Gwi7d31 No, f-strings are not a replacement for str.format(). For example, this answer ... More on stackoverflow.com
🌐 stackoverflow.com
Curly bracket in this code (beginner)
Inside an “f-string” those are references to variables. So it’ll swap in first and last into the full_name string on execution. More on reddit.com
🌐 r/learnpython
9
13
October 21, 2023
regex - surrounding a pattern in python string with brackets - Stack Overflow
I wrote a code that looks for the ... "-d" until I find whitespace or "{" and stop and add brackets. my code looks like this: P.S. I have many files that I read from them and try to modify the string there the example above is just for demonstrating what I'm trying to ... More on stackoverflow.com
🌐 stackoverflow.com
regex - Get the string within brackets in Python - Stack Overflow
2 Regular Expression that return matches specific strings in bracket and return its next and preceding string in brackets · 0 Python Parsing with a Variable Name and Square Brackets More on stackoverflow.com
🌐 stackoverflow.com
🌐
Edlitera
edlitera.com › blog › posts › python-parentheses
Python Parentheses Cheat Sheet | Edlitera
Example of assigning variable values using f-strings in Jupyter notebook: In this article, I've demonstrated some of the different uses for standard parentheses, square brackets, and curly braces in Python that you can use as a cheat sheet.
🌐
SheCanCode
shecancode.io › home › news & articles › string formatting in python
String Formatting in Python - SheCanCode
December 11, 2023 - In this example, the expression is given inside the curly brackets {a*2}. The value of a is doubled and then the output is displayed. Similarly, formatting the values can also be done. Here, in this example, we round off to two decimal places. Only in the f string formatting can we include expressions.
🌐
Data Science Discovery
discovery.cs.illinois.edu › guides › Python-Fundamentals › brackets
Parentheses, Square Brackets and Curly Braces in Python - Data Science Discovery
March 22, 2024 - Brief description on when to use parentheses `()`, square brackets `[]` and curly braces `{}` in python
Find elsewhere
🌐
Processing
py.processing.org › reference › indexbrackets.html
[] (Index brackets) \ Language (API)
Python Mode for Processing extends the Processing Development Environment with the Python programming language.
🌐
EnableGeek
enablegeek.com › home › print your (box,curly, parentheses) brackets in python
Print Your (Box,Curly, Parentheses) Brackets in Python - EnableGeek
March 21, 2024 - In Python, you can include curly braces (also known as braces or brackets) in a string by escaping them using a backslash (‘\‘). Though this is old method. You can write curly bracaes normally to print braces. Here’s an example:
🌐
AskPython
askpython.com › home › how to print brackets in python?
How to Print Brackets in Python? - AskPython
May 30, 2023 - Here, we used an empty string variable to print the brackets. We concatenated the bracket with the empty string and printed it.
🌐
Codecademy
codecademy.com › learn › dacp-python-fundamentals › modules › dscp-python-strings › cheatsheet
Python Fundamentals: Python Strings Cheatsheet | Codecademy
Python strings can be indexed using the same notation as lists, since strings are lists of characters. A single character can be accessed with bracket notation ([index]), or a substring can be accessed using slicing ([start:end]).
🌐
GeeksforGeeks
geeksforgeeks.org › python › parentheses-square-brackets-and-curly-braces-in-python
Parentheses, Square Brackets and Curly Braces in Python - GeeksforGeeks
July 26, 2025 - Python · my_list = [1, 2, 3, 4] ... to access elements in sequences like lists, strings, and tuples. For example, my_list[0] or my_string[1:4] ....
🌐
Django CAS
djangocas.dev › blog › python › python-literal-curly-braces-in-f-string
Python: How to print literal curly brace { or } in f-string and format string
July 10, 2024 - A single opening curly bracket '{' marks a replacement field, which starts with a Python expression. ... 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.
Top answer
1 of 2
5
>>> import re
>>> oldString = "this is my {{string-d}}"
>>> oldString2 = "this is my second{{ new_string-d }}"
>>> re.sub(r"(\w*-d)", r"(\1)", oldString)
'this is my {{(string-d)}}'
>>> re.sub(r"(\w*-d)", r"(\1)", oldString2)
'this is my second{{ (new_string-d) }}'

Note that this matches "words" assuming that a word is composed of only letters, numbers, and underscores.


Here's a more thorough breakdown of what's happening:

  • An r before a string literal means the string is a "raw string". It prevents Python from interpreting characters as an escape sequence. For instance, r"\n" is a slash followed by the letter n, rather than being interpreted as a single newline character. I like to use raw strings for my regex patterns, even though it's not always necessary.
  • the parentheses surrounding \w*-d is a capturing group. It indicates to the regex engine that the contents of the group should be saved for later use.
  • the sequence \w means "any alphanumeric character or underscore".
  • * means "zero or more of the preceding item". \w* together means "zero or more alphanumeric characters or underscores".
  • -d means "a hyphen followed by the letter d.

All together, (\w*-d) means "zero or more alphanumeric characters or underscores, followed by a hyphen and the letter d. Save all of these characters for later use."

The second string describes what the matched data should be replaced with. "\1" means "the contents of the first captured group". The parentheses are just regular parentheses. All together, (\1) in this context means "take the saved content from the captured group, surround it in parentheses, and put it back into the string".


If you want to match more characters than just alphanumeric and underscore, you can replace \w with whatever collection of characters you want to match.

>>> re.sub(r"([\w\.\[\]]*-d)", r"(\1)", "{{startingHere[zero1].my_string-d }}")
'{{(startingHere[zero1].my_string-d) }}'

If you also want to match words ending with "-d()", you can match a parentheses pair with \(\) and mark it as optional using ?.

>>> re.sub(r"([\w\.\[\]]*-d(\(\))?)", r"(\1)", "{{startingHere[zero1].my_string-d() }}")
'{{(startingHere[zero1].my_string-d()) }}'
2 of 2
0

If you want the bracketing to only take place inside double curly braces, you need something like this:

re.sub(r'({{\s*)([^}]*-d)(\s*}})', r'\1(\2)\3', s)

Breaking that down a bit:

# the target pattern
r'({{\s*)([^}]*-d)(\s*}})'
# ^^^^^^^ capture group 1, opening {{ plus optional space
#        ^^^^^^^^^ capture group 2, non-braces plus -d
#                 ^^^^^^^ capture 3, spaces plus closing }}

The replacement r'\1(\2)\3' just assembles the groups, with parenthesis around the middle one.

Putting it together:

import re

def quote_string_d(s):
    return re.sub(r'({{\s*)([^}]*-d)(\s*}})', r'\1(\2)\3', s)

print(quote_string_d("this is my {{string-d}}"))
print(quote_string_d("this is my second{{ new_string-d }}"))
print(quote_string_d("this should not be quoted other_string-d "))

Output:

this is my {{(string-d)}}
this is my second{{ (new_string-d) }}
this should not be quoted other_string-d 

Note the third instance does not get the parentheses, because it's not inside {{ }}.

🌐
w3resource
w3resource.com › python-exercises › class-exercises › python-class-exercise-3.php
Python: Validity of a string of parentheses - w3resource
Write a Python class to check the validity of a string of parentheses, '(', ')', '{', '}', '[' and ']. These brackets must be closed in the correct order, for example "()" and "()[]{}" are valid but "[)", "({[)]" and "{{{" are invalid.
🌐
Linux Hint
linuxhint.com › python-string-formatting-tutorial
Python String Formatting Tutorial
September 10, 2023 - Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
Python
docs.python.org › 3.3 › library › string.html
6.1. string — Common string operations — Python 3.3.7 documentation
March 9, 2022 - If it is an integer, it represents ... it is a string, then it represents a named argument in kwargs. The args parameter is set to the list of positional arguments to vformat(), and the kwargs parameter is set to the dictionary of keyword arguments. For compound field names, these functions are only called for the first component of the field name; Subsequent components are handled through normal attribute and indexing operations. So for example, the field ...
🌐
GeeksforGeeks
geeksforgeeks.org › python-extract-substrings-between-brackets
Extract substrings between brackets - Python - GeeksforGeeks
January 11, 2025 - Input : test_str = "gfg at 2021-01-04" Output : 2021-01-04 Explanation : Date format string found. Input : test_str = "2021-01-04 for gfg" Output : 2021-01-04 Explanation : Date format string found.