Print literal braces in Python format strings

Escape braces in f-strings and str.format, combine literal braces with substitutions, and serialize JSON without hand-built templates.

Best practices
Python programming and application logging

Double each literal brace in an f-string or a str.format() template: {{ produces {, and }} produces }. Braces used for substitution remain single.

Escape braces in str.format

print("{{example}}".format())     # {example}
print("{{{}}}".format("value"))   # {value}

In the second expression, {{ is an opening literal brace, {} is the replacement field, and }} is the closing literal brace.

Use the same rule in an f-string

name = "world"
print(f"{{hello}}")   # {hello}
print(f"{{{name}}}")  # {world}
print(f"{{{{")       # {{

The last example needs four opening braces to produce two literal ones. A raw f-string still processes braces: the r prefix changes backslash handling, not the replacement-field syntax.

Plain strings and percent formatting

print("{example}")                 # {example}
print("%s {example}" % "hello")    # hello {example}

Ordinary strings do not interpret braces. Percent formatting uses % directives, so braces do not need escaping there either.

Build JSON as data

For JSON, construct Python objects and let json.dumps handle quoting and escaping:

import json

payload = {"name": 'A "quoted" value', "enabled": True}
print(json.dumps(payload))

This avoids manually doubling the structural braces and correctly escapes values containing quotes, backslashes, or newlines. String concatenation or a generic template is not a substitute for a JSON serializer.

FAQ

Can I use dollar-sign placeholders instead? string.Template uses placeholders such as $name, leaving braces in ordinary text alone unless they form ${name}. It can be convenient for non-JSON templates, but does not automatically escape inserted values for JSON or HTML.

Why does an unmatched brace fail? In a formatted string, a single brace starts or ends a replacement field. Double it when you mean a literal character; do not try to escape it with a backslash.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting