Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping chars in f-string [duplicate]

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?

like image 214
user12282936 Avatar asked Sep 15 '25 07:09

user12282936


1 Answers

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).

like image 158
Carcigenicate Avatar answered Sep 17 '25 22:09

Carcigenicate