0

I have the following code;

#!/usr/bin/python3
# Connect to the database.
import pymysql
conn = pymysql.connect(
db='srt_test2',
user='root',
passwd='',
host='localhost')
c = conn.cursor()

# Print the contents of the database.
c.execute("SELECT * FROM users")
all_data = c.fetchall()
my_list = []
for item in all_data :
   my_list.append([item[1],item[4]])

my_page = """

<!DOCTYPE html>
   <html>
      <head>
         <title>HTML Tables</title>
   </head>
   <body>
     <table border="1">
{MY_TABLE}
      </table>
   </body>
</html>
"""
my_string = ""

for item in my_list :
   my_string += "      <tr>\n"
   for element in item :
       my_string += "         <td>" + str(element) + "</td>\n"
   my_string += "      </tr>\n"
# Print necessary headers.
print("Content-Type: text/html")
print()

print(my_page.format(MY_TABLE=my_string))

When I print element 1 how can I get it to have a title of "username" and when I print element 4 how can I get it to have a title of "grade" ? Thanks

user444
  • 21
  • 4

3 Answers3

2

You can use the th element, like so:

 <table border="1">
 <tr><th>username</th><th>grade</th></tr>
 {MY_TABLE}
  </table>
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0

Options:

1. String concatenation

  1. Template Strings

  2. A fully featured template system like jinja2

I would also recommend to use some kind of web framework.

Edit: I think I misunderstand your Question. #3 is still a valid option, and you can count your loop as shown here

0

If what you want is just to add title for your table's columns, you can initialize your my_string variable like this:

my_string = '<tr><th>username</th><th>grade</th></tr>'
ettanany
  • 19,038
  • 9
  • 47
  • 63