2016-12-01 38 views
0

我有以下代碼;使用python添加標題到HTML表格

#!/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)) 

當我打印單元1我怎樣才能得到它具有「用戶名」的稱號,並當我打印件4我怎樣才能得到它有「等級」的標題? 由於

+0

請首先修正您的代碼縮進 – ettanany

+0

您想在哪裏輸入用戶名和分數?在表頭或在同一個'​​'或另一列? – furas

回答

2

可以使用th元件,像這樣:

<table border="1"> 
<tr><th>username</th><th>grade</th></tr> 
{MY_TABLE} 
    </table> 
0

選項:

1. 字符串連接

  • Template Strings

  • 一個像jinja2

  • 功能齊全的模板系統我也建議使用某種類型的Web框架。

    編輯: 我想我誤解了你的問題。 #3仍然是一個有效的選擇,你可以 算你的循環,如圖here

    0

    如果你想要的僅僅是添加標題爲您的表列,就可以初始化你my_string變量是這樣的:

    my_string = '<tr><th>username</th><th>grade</th></tr>'