在urls.py
Django的
#urls.py
url(r'^topics/(?P<topic_id>\d+)/$', views.topic, name='topic')
The second part of the expression, /(?P<topic_id>\d+)/, matches an integer between two forward slashes and stores the integer value in an argument called topic_id.
我试图用正则表达式了解它
In [6]: re.findall(r'topics/(?P<topic_id>\d+)/$', "topics/1/")
Out[6]: ['1']
但是,当我尝试
In [7]: re.findall(r'topics/(?P<topic_id>\d+)/$', "topics/1/").topic_id
AttributeError: 'list' object has no attribute 'topic_id'
看来整数没有存储在中topic_id
,如何理解?
您的错误不是来自“ topic_id”,而是关于re
。
如果使用re.findall
,它将返回与您的正则表达式匹配的所有列表。
因此,您的情况re.findall(r'topics/(?P<topic_id>\d+)/$', "topics/1/")
将为['1']
。
因此,当然要['1'].topic_id
提高AttributeError。
如果要分组'topic_id'
,请这样做
p = re.match(r'topics/(?P<topic_id>\d+)/$', "topics/1/")
p.group('topic_id') # it returns '1'
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句