Explain Codes LogoExplain Codes Logo

How do I escape curly-brace ({}) characters in a string while using .format (or an f-string)?

python
formatting
strings
f-strings
Nikita BarsukovbyNikita Barsukov·Nov 3, 2024
TLDR

The simple method is to double the curly braces, {{ or }} for literal { or } within strings using .format and f-strings.

.format Quick Look:

# Brace yourself for escaping braces print("{{escaped braces}}".format())

f-string Quick Look:

# Time to f-escape, it's simpler than you think print(f"{{escaped braces}}")

The Why and When of it

Curly braces {} in Python are used for variables or values substitutions within strings. If you want them to appear as literal, dodge the special formatting tokens by doubling up each brace.

Going .format

The .format() method provides flexibility for data placement and output rotation:

  • Positional formatting: Swap places! "{1} {0}".format('world', 'Hello') -> 'Hello world'.
  • Keyword formatting: Name it and claim it! "{greeting} {addressee}".format(greeting='Hello', addressee='world') -> 'Hello world'.

Literal braces, though, still ask for double: print("{{Hello}} {0}".format('world')) -> {Hello} world.

Enter: f-string

Use the smaller and readable f-string (Python 3.6 and above) for formatting strings:

  • Inline expressions: No seating arrangement needed, name = "world"; f"Hello {name}" -> Hello world.
  • Efficiency: Being evaluated at runtime, f-strings race past the traditional methods.

For literals, the same rule applies: f"Hello {{world}}" -> Hello {world}.

Be aware, be prepared

Escaping sounds simple enough, but watch out for these scenarios:

  • Nested curly braces: Add one more brace for each complexity level - {, {{, {{{, {{{{, and so on...
  • Forget backslashes: Brace escaping in Python doesn't involve backslashes, contrary to popular opinion.
  • JSON handling: When dealing with JSON, use json.dumps() instead of string formatting to sidestep brace issues.

Taming the Formidable Formats

Format strings have {} as placeholder for replacement, but are flexible with positioning via {0}, {1}, etc., and can even accommodate variables and more complex expressions.

When using f-strings, encapsulate expressions that return a brace with triple braces: f'{{{expression}}}' to get a literal {expression} printed.

Going Beyond and Avoiding Pitfalls

Apart from simple texts, format strings are quite handy with dictionaries and lists, as well as unpacking expressions:

  • With dictionaries: data = {'name': 'Alice', 'age': 30}; "Name: {name}, Age: {age}".format(**data) gives Name: Alice, Age: 30
  • With lists: languages = ['Python', 'JavaScript']; "I love {0[0]} and {0[1]}".format(languages) gives I love Python and JavaScript

Ensure you're not missing any brace or have any extra ones and keep a track of your nested structures. Validate complex f-string expressions outside of the string itself to ensure that they deliver as expected.