Skip to main content
 首页 » 编程设计

python之如何连接字符串 for ... in ... (Python)

2025年05月04日26artech

我是一个c coder,但是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 

请您参考如下方法:

您在字符串连接中放置了逗号:

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) 

请注意,您根本不需要测试 items 中的每个项目,您只是已经从循环中的列表中获取了项目。这只是额外的工作,不会做任何事情。