How to escape curly-brackets in f-strings?

PythonPython 3.xCurly BracesF String

Python Problem Overview


I have a string in which I would like curly-brackets, but also take advantage of the f-strings feature. Is there some syntax that works for this?

Here are two ways it does not work. I would like to include the literal text {bar} as part of the string.

foo = "test"
fstring = f"{foo} {bar}"

NameError: name 'bar' is not defined

fstring = f"{foo} \{bar\}"

SyntaxError: f-string expression part cannot include a backslash

Desired result:

'test {bar}'

Edit: Looks like this question has the same answer as https://stackoverflow.com/questions/5466451/how-can-i-print-literal-curly-brace-characters-in-python-string-and-also-use-fo, but you can only know that if you know that str.format uses the same rules as the f-string. So hopefully this question has value in tying f-string searchers to this answer.

Python Solutions


Solution 1 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJDAndersView Question on Stackoverflow
Solution 1 - PythonwimView Answer on Stackoverflow