How to escape a single curly bracket in an f-string in Python?

Labo picture Labo · Apr 2, 2019 · Viewed 12.8k times · Source

I want to print a single curly bracket.

Example:

a = 2
>>> f"{'{'} {a}"
'{ 2'

How can I use less that 5 characters?

Not a duplicate of How can I print literal curly-brace characters in python string and also use .format on it?

Answer

Ralf picture Ralf · Apr 2, 2019

It is a duplicate of the question you linked. The doble curly brace is used to escape the curly brace.

>>> a = 2
>>> f'{{ {a}'                  # f-strings
'{ 2'
>>> '{{ {}'.format(a)          # str.format() with args
'{ 2'
>>> '{{ {a}'.format(a=2)       # str.format() with kwargs
'{ 2'