【问题标题】:how to loop through this template... I'd like to generate the items of a list如何循环浏览此模板...我想生成列表中的项目
【发布时间】:2021-07-12 00:34:48
【问题描述】:
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)

KeyError: 'i'

带有''的语法来自latex 我需要那个 3 {,以便代码在乳胶上正常运行。

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

我想生成这样的东西。

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

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

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

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

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

【问题讨论】:

  • 您需要\input{{{{i}}}} 进行替换,然后使用.format(i=i)。应该这样做。
  • 没用。循环没有返回错误,没有构造模板更改索引号

标签: python rawstring


【解决方案1】:

这是一个代码 sn-p,它又快又脏,但对我有用。

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

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

【讨论】:

  • 我需要用那个部分写一个文件...无法使用打印但得到了精神并实际解决了问题!非常感谢!!!!
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2020-10-14
    • 1970-01-01
    • 2020-06-07
    相关资源
    最近更新 更多