How to Escape Brackets (Curly Braces) in Python f-strings
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.
# ⛔️ Error: Python expects a variable named 'json_key', not a literal string
try:
print(f"{json_key}: value")
except NameError as e:
print(f"Error: {e}")
# ⛔️ Error: Unmatched braces cause syntax errors
# print(f" This is a set: {1, 2} ") # This evaluates the tuple (1, 2)
# print(f" { ") # SyntaxError: f-string: expecting '}'
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}.
# ✅ Solution: Double the braces to escape them
header = f"The syntax for a placeholder is {{variable}}."
print(header)
# Example: Printing a JSON-like string
key = "id"
val = 42
json_str = f'{{"{key}": {val}}}'
print(json_str)
Output:
The syntax for a placeholder is {variable}.
{"id": 42}
This escaping rule applies specifically to f-strings. In standard strings ("..."), braces do not need escaping. However, if you use .format(), the same double-brace rule applies.
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
# ✅ We want to print: "Coordinates: {10, 20}"
# 1. {{ and }} produce the outer literal braces
# 2. {x} and {y} are evaluated as variables
coord_msg = f"Coordinates: {{{x}, {y}}}"
print(coord_msg)
# A clearer example separating the logic
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:
{{creates the literal opening brace{.{value}evaluates the variable.}}creates the literal closing brace}.
value = "Python"
# ⛔️ Incorrect: Only evaluates the variable
print(f"{value}")
# ⛔️ Incorrect: Only prints the literal string "{value}"
print(f"{{value}}")
# ✅ Correct: Prints the variable wrapped in braces
print(f"{{{value}}}")
Output:
Python
{value}
{Python}
When dealing with complex multiline f-strings (like generating CSS or JSON), visually separate your literal braces from your expressions using spacing if possible, or build the string in parts to improve readability.
Conclusion
To handle brackets in Python f-strings correctly:
- Double the braces (
{{,}}) if you want them to appear as literal text in the output. - Use single braces (
{,}) if you want Python to evaluate the text inside as a variable or expression. - Use triple braces (
{{{,}}}) if you want to display a variable's value wrapped in brackets (e.g.,{Value}).