嵌套for循环与.format()的混淆。

问题描述 投票:1回答:1

期望产出。

<ul> 
<li>first string</li>
<li>second string</li>
</ul>

代码。

items = ['first string', 'second string']
html_str = "<ul>\n"          # The "\n" here is the end-of-line char, causing
                             # chars after this in html_str to be on next line

for item in items:
html_str += "<li>{}</li>\n".format(item)
html_str += "</ul>"

print(html_str)

对于上面的代码,我很困惑,为什么?

</ul>

只显示一次,而不是两次。换句话说,我不清楚为什么中间的两行("第一行 "和 "第二行")循环了两次,而最后一行只显示一次。

python html loops for-loop nested
1个回答
0
投票

我意识到问题出在for循环的缩进处。正确的代码应该是。

items = ['first string', 'second string']
html_str = "<ul>\n"          # The "\n" here is the end-of-line char, causing
                             # chars after this in html_str to be on next line

for item in items:
    html_str += "<li>{}</li>\n".format(item)
html_str += "</ul>"

print(html_str)

我被提醒了关于缩进在编程中的重要性。

© www.soinside.com 2019 - 2024. All rights reserved.