JDAnders JDAnders -4 years ago 219
Python Question

How to escape f-strings in python 3.6?

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 "

" 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}'

Answer Source

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

Use double curlies:

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download