期望产出。
<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>
只显示一次,而不是两次。换句话说,我不清楚为什么中间的两行("第一行 "和 "第二行")循环了两次,而最后一行只显示一次。
我意识到问题出在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)
我被提醒了关于缩进在编程中的重要性。