Search code examples
pythonformat

Escaping {} surrounding a variable to be formatted


I need to generate a string where the variable should end up between {}. For instance, the result should be

{0.05} and {4}

I tried to get this using

"{{}} and {{}}".format(0.05, 4)

However, this leads to

{} and {}

How can I escape { and } such that it does format it using the variables.


Solution

  • You escape by doubling. So do one more.

    "{{{}}} and {{{}}}".format(0.05, 4)
    f"{{{a}}} and {{{b}}}"
    "{{{a}}} and {{{b}}}".format(a=a, b=b)
    

    Note the Stack Overflow built-in highlight in f-string.

    For reference see https://docs.python.org/3/library/string.html#format-string-syntax .