user1795998
user1795998

Reputation: 5127

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?

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

Upvotes: 0

Views: 1078

Answers (4)

Eric
Eric

Reputation: 97641

Python does not have built in string interpolation. However, you can easily get what you want with "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.

Upvotes: 0

Marcin
Marcin

Reputation: 49856

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.

Upvotes: 0

Protagonist
Protagonist

Reputation: 502

You have to rebuild your string like this, because wikilinklis[i] changes for every iteration.

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

Upvotes: 2

mata
mata

Reputation: 69062

concatenate your strings:

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

if wikilinks is a python array of strings. Otherwise you have to escape the quotes (if you're trying to write 'wikilinks[i]' as a string).

Upvotes: 4

Related Questions