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

2
  • Please fix your code indentation first Commented Dec 1, 2016 at 19:24
  • where do you want "username" and "grade" ? In table header or in the same <td> or in another column ? Commented Dec 1, 2016 at 19:36

3 Answers 3

2

You can use the th element, like so:

 <table border="1">
 <tr><th>username</th><th>grade</th></tr>
 {MY_TABLE}
  </table>
Sign up to request clarification or add additional context in comments.

Comments

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>'

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.