Double each literal curly brace—writing {{ for { and }} for }—inside both f-strings (f"{{key: {val}}}") and str.format() templates ("{{key: {}}}".format(val)) so Python treats them as literal characters instead of replacement field delimiters.
Basic Example
name = "Alice"
score = 98
# 1. Recommended (f-strings): Double {{ and }} around literal braces
json_like = f'{{"user": "{name}", "score": {score}}}'
print(json_like)
# Output: {"user": "Alice", "score": 98}
# 2. str.format() with positional or named placeholders:
template = "Set literal: {{{0}, {1}}} -> template: {{key}}"
print(template.format(10, 20))
# Output: Set literal: {10, 20} -> template: {key}
# 3. Alternative for heavy-brace templates (JSON, CSS, LaTeX): use json.dumps() or string.Template
import json
print(json.dumps({"user": name, "score": score}))
# Output: {"user": "Alice", "score": 98}
Key Details & Edge Cases
- Triple braces (
{{{x}}}) combine a literal brace with a dynamic expression:- When a variable sits directly inside literal braces without spaces, write three braces (
{{{x}}}): the outer{{and}}render as literal{and}, while the inner{x}evaluatesx(x = 5; f"{{{x}}}"$\rightarrow$"{5}").
- When a variable sits directly inside literal braces without spaces, write three braces (
- Backslashes (
\{) do NOT escape braces in f-strings orstr.format():- Writing
f"\{x\}"or"\{0\}".format(x)still evaluates{x}/{0}as a placeholder and leaves literal backslashes around it ("\{5\}"), and writingf"\{"raisesSyntaxError: f-string: single '{' is not allowed. Always double the braces ({{/}}).
- Writing
- Avoid manual brace escaping when building JSON strings:
- Hand-writing
f'{{"msg": "{text}"}}'breaks iftextcontains quotes ("), newlines, or backslashes (risking invalid JSON or injection bugs). Always serialize dictionaries withjson.dumps({"msg": text})instead.
- Hand-writing
- Avoid
str.format()on untrusted user templates (KeyError/ attribute traversal):- Never call
user_supplied_str.format(**data)directly, as unescaped{in user text raisesValueError: Single '{' encountered in format stringor exposes object attributes ({user.__class__}). Usestring.Template(syntax, where{needs no escaping) or Jinja2 sandboxed templates for user-provided strings. - Format specifiers with dynamic width/precision (f"{val:{width}.{prec}f}"): - Nested single braces inside an expression’s format spec ({val:{width}d}) are evaluated dynamically as format parameters—not literal braces—whereas doubled braces outside the expression ({}) render literally. ### Comparison of Brace-Escaping & Alternative Formatting Techniques \vert} Method \vert{} Literal{and}Syntax \vert{} Dynamic Placeholder Syntax \vert{} Best Used When \vert{} \vert{} :— \vert{} :— \vert{} :— \vert{} :— \vert{} \vert{} f-string (f"...") (Recommended) \vert{}{{and}}\vert{}{expression}\vert{} Inline formatting with variables/expressions and only a few literal braces. \vert{} \vert{}str.format()("...".format(...)) \vert{}{{and}}\vert{}{}/{0}/{name}\vert{} Reusable format strings stored in variables, configs, or translation catalogs. \vert{} \vert{}string.Template()(no escaping needed) |$varor${var}| Templates with heavy curly braces (CSS, LaTeX, shell scripts) or untrusted format strings. | | **json.dumps(obj)** | Automatic (serialized fromdict) | Standard Pythondict` values | Generating valid JSON payloads safely without manual brace or quote escaping. |
- Never call
You must log in or register to comment.
