How do you escape curly braces {} inside Python str.format() and f-strings? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you escape curly braces {} inside Python str.format() and f-strings?

message-square
0

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} evaluates x (x = 5; f"{{{x}}}" $\rightarrow$ "{5}").
  • Backslashes (\{) do NOT escape braces in f-strings or str.format():
    • Writing f"\{x\}" or "\{0\}".format(x) still evaluates {x} / {0} as a placeholder and leaves literal backslashes around it ("\{5\}"), and writing f"\{" raises SyntaxError: f-string: single '{' is not allowed. Always double the braces ({{ / }}).
  • Avoid manual brace escaping when building JSON strings:
    • Hand-writing f'{{"msg": "{text}"}}' breaks if text contains quotes ("), newlines, or backslashes (risking invalid JSON or injection bugs). Always serialize dictionaries with json.dumps({"msg": text}) instead.
  • Avoid str.format() on untrusted user templates (KeyError / attribute traversal):
    • Never call user_supplied_str.format(**data) directly, as unescaped { in user text raises ValueError: Single '{' encountered in format string or exposes object attributes ({user.__class__}). Use string.Template ($var 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 ($var) { and `(no escaping needed) |$varor${var} | Templates with heavy curly braces (CSS, LaTeX, shell scripts) or untrusted format strings. | | **json.dumps(obj)** | Automatic (serialized from dict) | Standard Python dict` values | Generating valid JSON payloads safely without manual brace or quote escaping. |