在Python中访问for循环的索引

2024-04-26 13:26:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着从一个文本文件中读取文件中的每一行。它起作用了。但实际上我想为每一行添加一个索引。你知道吗

我有以下代码:

视图.py

def survey(request):

myFile = open(r'd:\work\Python\ps\psi\questions.txt', 'r')
out = myFile.readlines()

return render_to_response("questions.html", {'f' : out})

问题.html

{%  for line in f %}

  #here I would like to add an index, for instance :
  # 1.Question1 text
  # 2.Question2 text
  {{ line }}<br>

{% endfor %}

我尝试使用enumarate(f)使用以下代码:

{%  for index, line in enumerate(f) %}
            {{index }}.{{ line }}<br>
{% endfor %}

但是,它不起作用。我得到错误:Could not parse the remainder: '(f)' from 'enumerate(f)'。你知道吗

有什么想法吗? 谢谢。你知道吗


Tags: to代码textinbrforindexhtml
1条回答
网友
1楼 · 发布于 2024-04-26 13:26:36

您不应该将python代码放在模板中,您可以使用Django

{{ forloop.counter }}

对于从1开始的索引,或

{{ forloop.counter0 }}

对于基于0的索引。你知道吗

Docs。你知道吗

相关问题 更多 >