1

I have a template in which some variables shall be replaced. As the template shall be for C-source code, it contains brackets { and }. The python formatter, which is used for replacing is breaking on these brackets. Is there any way to escape those brackets that shall be kept in the result text?

Minimum example:

template = """
 Here is some text
 Here is something to insert {name}
 And here is a { 
 and later there is a }
"""

settings = {'name': "John"}
print( template.format(**settings) )

My target result is:

 Here is some text
 Here is something to insert John
 And here is a { 
 and later there is a }

The actual result is a python error:

Traceback (most recent call last):
  File "minimum.py", line 9, in <module>
    print( template.format(**settings) )
KeyError: ' \n and later there is a '
meddle0106
  • 1,292
  • 1
  • 11
  • 22

4 Answers4

3

When you need literal { and } in .format-ed str you should use {{ and }} as follows:

template = """There is {name}
and here is a {{
an later there is a }}"""
settings = {'name': "John"}
print(template.format(**settings))

output:

There is John
and here is a {
an later there is a }

If you want to know more about .format beyond If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}. then read documentation about Format String Syntax.

Daweo
  • 31,313
  • 3
  • 12
  • 25
1

Use {{ when you want a literal { to be printed. Same for }} and }.

template = """
 Here is some text
 Here is something to insert {name}
 And here is a {{ 
 and later there is a }}
"""

settings = {'name': "John"}
print( template.format(**settings) )

Note: this same syntax applies to f-strings (introduced in python 3.6)

settings = {'name': "John"}
print(f"""
 Here is some text
 Here is something to insert {settings['name']}
 And here is a {{ 
 and later there is a }}
"""
)
Adirio
  • 5,040
  • 1
  • 14
  • 26
0

You can do it like this:

template = """
 Here is some text
 Here is something to insert {name}
 And here is a {{ 
 and later there is a }}
"""

settings = {'name': "John"}
print( template.format(**settings) )

Sorround the { and later there is a } with { }.

Take a look to the reference

Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

Carlo Zanocco
  • 1,967
  • 4
  • 18
  • 31
0

Using format strings requires doubling of all { and }, which is additional work and can lead to mistakes. Instead, a Template String can be used:

from string import Template

template = """
 Here is some text
 Here is something to insert $name
 And here is a { 
 and later there is a }
"""

settings = {'name': "John"}
print( Template(template).substitute(**settings) )
Wups
  • 2,489
  • 1
  • 6
  • 17