The Python Oracle

How to escape curly-brackets in f-strings?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC O Beethoven - Piano Sonata No 3 in C

--

Chapters
00:00 Question
01:13 Accepted answer (Score 387)
01:38 Thank you

--

Full question
https://stackoverflow.com/questions/4252...

Question links:
[How can I print literal curly-brace characters in a string and also use .format on it?]: https://stackoverflow.com/questions/5466...

Accepted answer links:
[same trick]: https://stackoverflow.com/q/5466451/6740...
[here]: https://www.python.org/dev/peps/pep-0498...
[here]: https://docs.python.org/3/reference/lexi...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python3x #curlybraces #fstring

#avk47



ACCEPTED ANSWER

Score 510


Although there is a custom syntax error from the parser, the same trick works as for calling .format on regular strings.

Use double curlies:

>>> foo = 'test'
>>> f'{foo} {{bar}}'
'test {bar}'

It's mentioned in the spec here and the docs here.