Search code examples
pythonrawstring

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


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}}}

Solution

  • 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)