escape single bracket in f-string

Viewed 2003

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.

3 Answers

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}

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

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

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