其他人已经指出了您的错误消息的原因。我已经冒昧地重新编写了代码。我所做的主要工作是避免字符串连接-在Python中,字符串是不可变的,因此连接需要创建一个完整的新字符串。避免这种情况的一种常见方法是将字符串片段放入一个列表中,然后使用字符串的join()方法将列表中的所有元素连接在一起。在
另一个主要的变化是使用string.format()方法来创建片段。在items = [
["/ank/homepage.py","Home"],
["/ank/package.py","Packages"],
["/status.py","Status"],
["/task.py","Task"],
["/report.py","Report"]
]
# Start a list of fragments with the start of the table.
html_fragments = [
'
]
for item in items:
# No need for the 'if item in items' here - we are iterating
# over the list, so we know its in the list.
#
# Also, this ifinstance() test is only required if you cannot
# guarantee the format of the input. I have changed it to allow
# tuples as well as lists.
if isinstance(item, (list, tuple)):
# Use string formatting to create the row, and add it to
# the list of fragments.
html_fragments.append('
{1:s}'.format(*item))# Finish the table.
html_fragments.append ('
')# Join the fragments to create the final string. Each fragment
# will be separated by a newline in this case. If you wanted it
# all on one line, change it to ''.join(html_fragments).
print '\n'.join(html_fragments)
我得到的结果是:
^{pr2}$