2

I am writing HTML to a file, suddenly I came accross this problem here:

theBody = "<h1>example</h1>"
with open("/home/mathew/Desktop/finalText.html", "w") as output:
        print("""<!doctype html>
        <html>
        <head>
        <style>
        body{
        background: #000;
        color: #fff;
        font-size: 2em;
        }
        </style>
        </head>
        <body>
        {}
        </body>
        </html>
        """.format(theBody), file=output)

The error I am facing is:

Traceback (most recent call last):
  File "/root/PycharmProjects/API/index.py", line 14, in <module>
    print("""<!doctype html>
KeyError: '\n    background'
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
Mathew
  • 129
  • 9

2 Answers2

1

You just need to use double brace for everything that format should ignore, e.g.

>>> print('{{ignore}}{}'.format('foo'))
{ignore}foo
adrtam
  • 6,991
  • 2
  • 12
  • 27
0

As mentioned in the accepted answer of this question, you have to double the { and } characters that are not placeholders. In your case:

body{{
 background: #000;
 color: #fff;
 font-size: 2em;
 }}
CCBet
  • 416
  • 1
  • 6
  • 19