3

I am trying to print a string in the following format:

"rob: {color: red  , number: 4}"

using an f-string to fill three values:

f"{name}: color: {color}  , number: {number}" #missing brackets

this would print:

"rob: color: red  , number: 4" #missing brackets

but I have no idea how to escape a single bracket the way I need to. I know {{}} lets you escape brackets, but this would print both at the same place in the string. I tried { { } and { } } in their respective spots but this just threw an error.

Justin
  • 1,329
  • 3
  • 16
  • 25

3 Answers3

5

Goal:

"rob: {color: red  , number: 4}"

Accomplished:

>>> name = 'rob'
>>> color = 'red'
>>> number = 4
>>> print(f"{name}: {{color: {color} , number: {number}}}")
rob: {color: red , number: 4}
Maximilian Burszley
  • 18,243
  • 4
  • 34
  • 63
3

Use double brackets when you want to show them, and single brackers for variables. See this post

f"{name}: {{color: {color}  , number: {number} }}" 
Rusty Robot
  • 1,725
  • 2
  • 13
  • 29
2

You can evaluate the string literal '{' and the string literal '}' inside the f-string, by wrapping them with braces to do the evaluation:

f"{name}: {'{'}color: {color}, number: {number}{'}'}"

Example:

>>> name = 'bob'
>>> color = 'red'
>>> number = 4
>>> f"{name}: {'{'}color: {color}, number: {number}{'}'}"
'bob: {color: red, number: 4}'
kaya3
  • 47,440
  • 4
  • 68
  • 97
  • Yes, your solution is the same as Rusty Robot's, which was posted before mine and yours. I just showed an alternative solution. – kaya3 Feb 27 '20 at 01:43
  • No, it was edited a few minutes before. You can sort the answers by last activity, and observe that Rusty Robot's answer appears last despite the edit. – kaya3 Feb 27 '20 at 11:24
  • I did check the timestamps when I made my comment; Rusty Robot's edit was made about 3 minutes before TheIncorrigible1 posted their answer, and about 4 minutes before I posted mine. If you inspect the source you can see the timestamps are 2020-02-27 01:32:34Z for Rusty Robot's edit, and 2020-02-27 01:36:23Z for TheIncorrigible1's answer. – kaya3 Feb 27 '20 at 12:19