如何连接字符串for ... in ...? (蟒蛇)

时间:2013-01-04 07:21:04

标签: python string

我是一名编码人员,但是python不同,我遇到了一个关于这个问题的问题

items = [
     ["/ank/homepage.py","Home"],
     ["/ank/package.py","Packages"],
     ["/status.py","Status"],
     ["/task.py","Task"],
     ["/report.py","Report"]
]

static_html='<table id="main_nav" align="center"><tr>'

for each_item in items:
    if each_item in items:
        if isinstance(each_item, list):
            static_html=  static_html + '<td><a href=" ', each_item[0], ' "> ', each_item[1], ' </a></th> '

static_html+='</tr></table>'

print static_html

然后,IDE发给我一个错误/usr/bin/python2.7

/home/tsuibin/code/aps/dxx/test_tmp.py
Traceback (most recent call last):
  File "/home/tsuibin/code/aps/dxx/test_tmp.py", line 39, in <module>
    printMainNavigation()
  File "/home/tsuibin/code/aps/dxx/test_tmp.py", line 20, in printMainNavigation
    static_html=  static_html + '<td><a href=" ', each_item[0], ' "> ', each_item[1], ' </a></th> '
TypeError: can only concatenate tuple (not "str") to tuple
Process finished with exit code 1

2 个答案:

答案 0 :(得分:5)

你在字符串连接中加入逗号:

static_html=  static_html + '<td><a href=" ', each_item[0], ' "> ', each_item[1], ' </a></th> '
因此,Python将这些元素视为元组(str0 + (str1, str2, str3))。请改用+

static_html=  static_html + '<td><a href=" ' + each_item[0] + ' "> ' + each_item[1] + ' </a></th> '

更好的是,使用字符串格式:

static_html += '<td><a href="{0[0]}"> {0[1]} </a></th> '.format(each_item)

在python中连接一系列字符串时,使用list()作为中介实际上会更快。构建列表,然后使用''.join()获取输出:

static_html = ['<table id="main_nav" align="center"><tr>']
for each_item in items:
     static_html.append('<td><a href="{0[0]}"> {0[1]} </a></th> '.format(each_item))

static_html.append('</tr></table>')
static_html = ''.join(static_html)

请注意,您根本不需要测试 each_item in items,您只需从循环列表中获取该项目。这只是额外的工作,没有做任何事情。

答案 1 :(得分:4)

其他人已经指出了您的错误消息的原因。我冒昧地重写了一下代码。我做的主要是避免字符串连接 - 在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 = [
    '<table id="main_nav" align="center"><tr>'
]

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('<td><a href="{0:s}">{1:s}</a></td>'.format(*item))

# Finish the table.
html_fragments.append ('</tr></table>')

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

我得到的输出:

<table id="main_nav" align="center"><tr>
<td><a href="/ank/homepage.py">Home</a></td>
<td><a href="/ank/package.py">Packages</a></td>
<td><a href="/status.py">Status</a></td>
<td><a href="/task.py">Task</a></td>
<td><a href="/report.py">Report</a></td>
</tr></table>