【问题标题】:Nested for loop confusion with .format()嵌套 for 循环混淆与 .format()
【发布时间】:2020-05-12 16:51:09
【问题描述】:

期望的输出:

<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】:

我意识到问题在于 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)

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

【讨论】:

  • @Gabip 感谢您提供正确的术语 - 缩进。
猜你喜欢
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-16
  • 2016-06-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多