如何遍历这个模板...我想生成一个列表的项目

问题描述

question_template =r''' 
%-----------------QUESTION-----------------------------------------
\item 
\input{{{i}}}
\n
'''
for i in range(0,10):
    question_template+=question_template.format(i)

我收到此错误


KeyError Traceback(最近一次调用最后一次) 在 6 ''' 7 for i in range(0,10): ----> 8 question_template+=question_template.format(i)

错误:'我'

带有 '' 的语法来自于 Latex 我需要 3 {,以便在乳胶上正确运行代码

这是一个根据文件夹中存储的问题生成考试的脚本。我想遍历文件夹并根据文件夹中的问题数量生成各种问题。

我想生成这样的东西。

''' 
%-----------------QUESTION-----------------------------------------
\item 
\input{{{0}}}

%------------------QUESTION------------------------------------------
\item 
\input{const regex = /^function(.*?)^end$/gms;
}

%----------------QUESTION--------------------------------------------
\item 
\input{{{2}}}

%-----------------QUESTION-----------------------------------------------
\item 
\input{dbutils}

%----------------QUESTION---------------------------------------------
\item 
\input{{{4}}}

解决方法

这是一个代码片段,它既快速又脏,但对我有用。

question_template =r''' 
%-----------------QUESTION-----------------------------------------
\item 
\input{{{'''

part2 = '''}}}
\n
'''
for i in range(0,10):
    print(question_template,i,part2)

,

您每次都在修改模板,而不是构建新字符串。这有效。

question_template =r''' 
%-----------------QUESTION-----------------------------------------
\item 
\input{{{i}}}
\n
'''
qt = ''
for i in range(0,10):
    qt+=question_template.format(i=i)
print(qt)