Skip to content

How to Escape Brackets (Curly Braces) in Python f-strings

Learn how to properly escape curly braces in Python f-strings to display literal {} characters while mixing dynamic expressions for JSON, CSS, or mathematical formatting.

Introduced in Python 3.6, f-strings (formatted string literals) provide a concise way to embed expressions inside string literals using curly braces {}. However, scenarios often arise, such as working with JSON strings, CSS, or mathematical sets, where you need to print literal braces rather than evaluating them as code.

This guide explains the syntax rules for escaping brackets in f-strings, how to mix literal braces with dynamic variables, and how to handle advanced formatting scenarios.

Understanding the Syntax Conflict

In an f-string, Python interprets any text inside single curly braces {...} as executable code (an expression). If you want to print a literal bracket, Python will get confused and likely raise a SyntaxError because it expects a variable or expression to follow the opening brace.

try:
    print(f"{json_key}: value")
except NameError as e:
    print(f"Error: {e}")

Output:

Error: name 'json_key' is not defined

Method 1: Escaping with Double Braces

To display a literal curly brace in an f-string, you must double the character.

  • Use {{ to print a literal {.
  • Use }} to print a literal }.
header = f"The syntax for a placeholder is {{variable}}."
print(header)

key = "id"
val = 42
json_str = f'{{"{key}": {val}}}'
print(json_str)

Output:

The syntax for a placeholder is {variable}.
{"id": 42}

Method 2: Mixing Literals and Expressions

You often need to combine literal braces with actual dynamic expressions. The syntax allows you to mix {{ (escaped) and { (expression) in the same string.

x = 10
y = 20

coord_msg = f"Coordinates: {{{x}, {y}}}"

print(coord_msg)

math_msg = f"The sum of {{x}} and {{y}} is {x + y}."
print(math_msg)

Output:

Coordinates: {10, 20}
The sum of {x} and {y} is 30.

Advanced: Triple Braces (Wrapping Variables)

A common point of confusion is "wrapping" a variable value in braces. For example, if value = 5, and you want the output {5}.

You need three braces:

  1. {{ creates the literal opening brace {.
  2. {value} evaluates the variable.
  3. }} creates the literal closing brace }.
value = "Python"

print(f"{value}") 

print(f"{{value}}")

print(f"{{{value}}}")

Output:

Python
{value}
{Python}

Conclusion

To handle brackets in Python f-strings correctly:

  1. Double the braces ({{, }}) if you want them to appear as literal text in the output.
  2. Use single braces ({, }) if you want Python to evaluate the text inside as a variable or expression.
  3. Use triple braces ({{{, }}}) if you want to display a variable's value wrapped in brackets (e.g., {Value}).
Navigation