4

I have run into the following issue with the f-string:

>>> a='hello'

# how to print '{hello}' ?

>>> f'{{a}}'
'{a}'

>>> f'\{{a}\}'
  File "<stdin>", line 1
SyntaxError: f-string: single '}' is not allowed

# doing it without f-strings
>>> '{' + a + '}'
'{hello}'

How do I escape chars in an fstring?

user12282936
  • 167
  • 2
  • 7
  • Double braces become a single brace on output, and you want the normal action of braces too, so try triple braces - `f'{{{a}}}'`. – jasonharper Nov 02 '19 at 01:17

1 Answers1

10

You need triple braces:

f'{{{a}}}'

The two outer {}s "escape" and evaluate to {...}, then the inner {} is used for formatting (or at least that's how I interpret it).

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117