173

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 How can I print literal curly-brace characters in a string and also use .format on it?, 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.

wjandrea
  • 23,210
  • 7
  • 49
  • 68
JDAnders
  • 3,321
  • 4
  • 9
  • 8
  • 13
    you can replace '{' and '}' to their corresponding codepoint `\u007b` and `\u007d`.For example `print(' \u007b \u007d')` got `{ }` – XX 吕 Jul 11 '19 at 11:12
  • 1
    This should actually be an/the answer because the doubling the braces does not work if you want to print a single brace. Oh my do I feel dirty now. – stefanct Jul 10 '21 at 14:57
  • 1
    @stefanct What do you mean does not work? `f'{{1{2}'` correctly returns `'{12'`, doesn't it? – wim Oct 07 '21 at 00:16
  • 1
    Yes, but there are lots of cases where it does not work, e.g., `f'{{}'` -> `SyntaxError: f-string: single '}' is not allowed` – stefanct Oct 07 '21 at 04:15
  • 1
    @stefanct still not seeing the problem - what do you think that should return? why using an f prefix at all if you’re not formatting any fields? – wim Oct 07 '21 at 14:44
  • you are missing the point. it does not work with fields either. i don't know why it works with your examples - probably some funny parser quirk with numeric literals but single parentheses are not universally supported in f-strings. – stefanct Oct 07 '21 at 17:02
  • 2
    Yes I am missing the point because you haven't showed an example of what you mean. Formatting a single brace 'not working' is clearly incorrect, `f"{{{name}"` gives a formatted string with a single leading brace, and has nothing to do with numeric literals. – wim Oct 07 '21 at 18:32

1 Answers1

279

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.

Arthur Tacca
  • 7,729
  • 1
  • 28
  • 46
wim
  • 302,178
  • 90
  • 548
  • 690