how to loop through this template... I'd like to generate the items of a list

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

I'm getting this error.


KeyError Traceback (most recent call last) in 6 ''' 7 for i in range(0,10): ----> 8 question_template+=question_template.format(i)

KeyError: 'i'

the syntax with the '' is from latex I need that 3 {, for the code run on the latex properly.

It's a script that generates exams based on questions stored in a folder. I want to run through the folder and generate various questions depending on the number of questions in the folder.

I'd like to generate something like this.

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

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

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

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

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

There are 2 answers

1
Austin Schaaf On BEST ANSWER

Here is a code snippet, that is quick and dirty but worked for me.

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

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

0
Tim Roberts On

You were modifying the template each time, instead of building a new string. This works.

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