写一个 for
循环,用于遍历字符串列表并创建单个字符串 html_str
,它是一个 HTML 列表。例如,如果列表是 items = ['first string', 'second string]
,输出 html_str
应该会输出:
<ul>
<li>first string</li>
<li>second string</li>
</ul>
即该字符串的第一行应该是起始标记 <ul>
。然后是源列表中的每个元素各占一行,两边是 <li>
和 </li>
标记。该字符串的最后一行应该是结束标记 </ul>
。
items = ['first string', 'second string']
html_str = "<ul>\n" # "\ n" is the character that marks the end of the line, it does
# the characters that are after it in html_str are on the next line
# write your code here
for item in items:
if item == 'first string' or item == 'second string':
html_str += "<li>" +item+"</li>\n"
html_str += "</ul>"
print(html_str)
优化后:
items = ['first string', 'second string']
html_str = "<ul>\n"
for item in items:
html_str += "<li>{}</li>\n".format(item)
html_str += "</ul>"
print(html_str)