Python:引用表中的行

时间:2010-11-11 02:01:20

标签: python html html-table

我正在尝试从文件中取出行并将它们放入将在Web上显示的表中。我需要能够单独引用这些行来使用if ... else语句来改变表信息。

任何人都可以帮我找到一种方法来引用它们 - 这是我的代码到目前为止。

#for each line in emaildomains - print out on page to view
print '<form method=\'post\' name="updateUsers">'
print '<table border="1">'
print '<tr>'
print '<th>Email Address</th>'
print '<th>Delete Email</th>'
print '<th>Make Changes?</th>'
print '</tr>'
n=1
for line in emaildomains:
    print '<tr>'
    print '<td><input type="text" name=\"useraddress\", n, value ="%s">' %line
    print '<input type="hidden" name=useraddress_org value ="%s"></td>' %line
    print '<td><input type=\"radio\" name=\"deleteRadio\", n, style=margin-left:50px></td>'
    print '<td><input type="submit" value="Edit Users" /></td>'
    print '</tr>'
    n+=1
print '</table>'
print '</form>'

2 个答案:

答案 0 :(得分:2)

为每个表条目(或行,根据您的需要)设置id HTML属性。 E.g。

<tr id="Foo">

答案 1 :(得分:0)

使用格式字符串对您有利。例如,如果我想有条件地添加问候语,我会将变量默认为空字符串并根据我的心情进行更改。也:

  • 不要实例化和维护计数器,而应考虑使用enumerate()。
  • 尽量避开逃脱的角色。
  • 保持干净一致的风格(即你有一些html属性使用',一些使用',一个没有使用任何东西)。

示例:

#for each line in emaildomains - print out on page to view
table_fs = """
<form method="post" name="updateUsers">
%s
<table border="1">
<tr>
<th>Email Address</th>
<th>Delete Email</th>
<th>Make Changes?</th>
</tr>
%s
</table>
</form>
"""

line_fs = """
<td>
  %s
  <input type="text" name="useraddress" %s value ="%s">
  <input type="hidden" name="useraddress_org" value ="%s">
</td>
<td><input type="radio" name="deleteRadio", n, style=margin-left:50px></td>
<td><input type="submit" value="Edit Users" /></td>
"""

good_mood = ''
if i_have_cookies:
    good_mood = '<h1>I LOVE COOKIES!</h1>'

lines = []
for n, line in enumerate(emaildomains, 1):
    greeting = ''
    if i_like_this_persion:
        greeting = 'Hi!'
    line = []
    line.append(line_fs%(greeting, n, line, line))
    cells_string = '\n'.join(['<td>%s</td>'%x for x in line])
    row_string = '<tr>%s</tr>'%(cells_string)
    lines.append(row_string)

rows_string = '\n'.join(lines)
print table_fs%(good_mood, rows_string)

P.S。这有点晚了,我有点累了,所以如果我不能拼写,或者我错过了什么,我很抱歉。