簡體   English   中英

如何在…中連接字符串? (蟒蛇)

[英]how to connection string in for … in … ? (python)

我是交流編碼器,但是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)

請注意,您根本不需要測試 each_item in items中的each_item in items ,只需從循環中的列表中獲得項目即可。 那只是多余的工作,什么都不做。

其他人指出了您的錯誤消息的原因。 我已經自由地重寫了一些代碼。 我要做的主要事情是避免字符串連接-在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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM