简体   繁体   English

Python中HTML代码的语法错误

[英]Syntax error with HTML code in python

I am trying to construct a HTML table in python and running into the following syntax error,can anyone please point what is the issue here? 我正在尝试在python中构建HTML表并遇到以下语法错误,有人可以在这里指出问题是什么吗?

for i in range(len(PLlis)):
    print "i"
    print i
    outstring += "<tr>\n"
    outstring += "<td><a href="wikilinklis[i]">PLlist[0]</a></td>\n"
    outstring += "<td>build_locationlis[i]</td>\n"
    outstring += "<td>lis[i]</td>\n"
    outstring += "<td>Host_loc</td>\n"
    outstring += "<td>Baselis[i]</td>\n"
    outstring += "</tr>\n"
outstring += "</table>\n"
return outstring

SYNTAX ERROR:- 语法错误:-

   outstring += "<td><a href="wikilinklis[i]">PLlist[0]</a></td>\n"
                                     ^

SyntaxError: invalid syntax SyntaxError:语法无效

concatenate your strings: 连接字符串:

outstring += "<td><a href=" + wikilinklis[i] + ">PLlist[0]</a></td>\n"

if wikilinks is a python array of strings. 如果wikilinks是一个python字符串数组。 Otherwise you have to escape the quotes (if you're trying to write 'wikilinks[i]' as a string). 否则,您必须转义引号(如果您尝试将“ wikilinks [i]”写为字符串)。

您必须像这样重建字符串,因为wikilinklis [i]每次迭代都会更改。

outstring += "<td><a href=%s>%s</a></td>\n" % (wikilinklis[i], PLlist[0])

Python does not have built in string interpolation. Python没有内置的字符串插值。 However, you can easily get what you want with "formatstring".format(...) 但是,您可以使用"formatstring".format(...)轻松获得所需的内容

for i in range(len(PLlis)):
    print "i"
    print i
    outstring += """
    <tr>
        <td><a href="{wikilink}">{PLlist[0]}</a></td>
        <td>{build_location}</td>
        <td>{value}</td>
        <td>Host_loc</td>
        <td>{base}</td>
    </tr>""".format(
        wikilink=wikilinklis[i],
        build_location=build_locationlis[i],
        value=lis[i],
        base=Baselis[i]
    )

outstring += "</table>\n"
return outstring

The triple quote have no meaning other than to allow me to span a string over multiple lines. 三重引号除了让我将字符串跨越多行外没有其他意义。

Don't do what you're doing. 不要做你在做什么。 Instead of concatenating a bunch of strings, you want to substitute values into a template. 您不想将一串字符串连接在一起,而是希望将值替换为模板。

The simplest way to do that is with a string, and the % operator: 最简单的方法是使用字符串和%运算符:

"""
<tr>
<td><a href="%(wikilinklis)s">%(PLlist)s</a></td>
<td>%(build_locationlis)s</td>
</tr>
""" % {'wikilinks': 'http://foo', 'PLlist': 'A link' }

Note the triple-quotes, which allow you to embed newlines and quotes. 注意三引号,它允许您嵌入换行符和引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM