使用迭代和 String.Format 创建文本块
Create blocks of text using iteration and String.Format
我能做到:
>>>some_string = 'this is {0} a {1}'
>>>print(some_string.format('totally', 'string'))
>>>this is totally a string
我想做的是形成一个 html 列表。我有什么办法可以做 类似...
my_list_items = ['<li>One</li>', '<li>Two</li>', '<li>Three</li>']
my_list = """<ol>
{list}
</ol>"""
print(my_list).format(list=my_list_items)
并得到
<ol>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ol>
理由是;我正在为我的学校写一个小的 cgi 应用程序。我宁愿能够保留模板 html 页面并在 cgi 脚本以下面的方式调用页面时插入正确的值,而不是在 cgi 文件本身中进行十亿次 print
调用,因为那太草率了并且难以调试。
group = '11bg/En1'
AP = 'AP1'
def process_input(group, AP):
"""
Any processing necessary, followed by calling the template and inserting the values
"""
return read_file('pages/group_page.html').format(group=group, AP=AP)
print(process_input(group, AP))
我立即意识到我是个白痴。当然只是把列表变成一个字符串。
我能做到:
>>>some_string = 'this is {0} a {1}'
>>>print(some_string.format('totally', 'string'))
>>>this is totally a string
我想做的是形成一个 html 列表。我有什么办法可以做 类似...
my_list_items = ['<li>One</li>', '<li>Two</li>', '<li>Three</li>']
my_list = """<ol>
{list}
</ol>"""
print(my_list).format(list=my_list_items)
并得到
<ol>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ol>
理由是;我正在为我的学校写一个小的 cgi 应用程序。我宁愿能够保留模板 html 页面并在 cgi 脚本以下面的方式调用页面时插入正确的值,而不是在 cgi 文件本身中进行十亿次 print
调用,因为那太草率了并且难以调试。
group = '11bg/En1'
AP = 'AP1'
def process_input(group, AP):
"""
Any processing necessary, followed by calling the template and inserting the values
"""
return read_file('pages/group_page.html').format(group=group, AP=AP)
print(process_input(group, AP))
我立即意识到我是个白痴。当然只是把列表变成一个字符串。