Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyError: '\n border' in adding variable in an HTML

A simple table that I want to include in an HTML email that sending by Python.

html = """
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;}
th, td {padding: 5px;}
th {text-align: left;}
</style>
</head>
<body>

<h2>Basic HTML Table</h2>

<table style="width:10%">
  <tr>
    <th>Firstname</th>
  </tr>
  <tr>
    <td>Jill</td>
  </tr>
  <tr>
    <td>Eve</td>
  </tr>
</table>

</body>
</html>
"""

It works fine, then I want to insert a variable into, so change it to:

code = "Somebody"
html = """

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;}
th, td {padding: 5px;}
th {text-align: left;}
</style>
</head>
<body>

<h2>Basic HTML Table</h2>

<table style="width:10%">
  <tr>
    <th>Firstname</th>
  </tr>
  <tr>
    <td>Jill</td>
  </tr>
  <tr>
    <td>{code}</td>
  </tr>
</table>

</body>
</html>
""".format(code=code)

It warns:

    """.format(code=code)
KeyError: '\n  border'

I was thinking to add html = html.readline.rstrip("\n") but the error happens even before that.

How can I have it corrected?

like image 530
Mark K Avatar asked Nov 16 '25 04:11

Mark K


2 Answers

As Tal said you need {} inside {}

For example : {{}}

code = "Somebody"
html = """

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {{
  border: 1px solid black;
  border-collapse: collapse;
}}
th, td {{padding: 5px;}}
th {{text-align: left;}}
</style>
</head>
<body>

<h2>Basic HTML Table</h2>

<table style="width:10%">
  <tr>
    <th>Firstname</th>
  </tr>
  <tr>
    <td>Jill</td>
  </tr>
  <tr>
    <td>{code}</td>
  </tr>
</table>

</body>
</html>
""".format(code=code)


print(html)
like image 63
Hong승원 Avatar answered Nov 17 '25 18:11

Hong승원


That's because you have a style block in there, and it is using the {} which are searched and evaluated by the .format() function.
Try removing it from the html by exporting it to a separated file.

like image 40
Tal Avatar answered Nov 17 '25 17:11

Tal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!