检索存储在(?P <topic_id>\d +)中的整数

Alg*_*bra 3 python django

urls.pyDjango

#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.
Run Code Online (Sandbox Code Playgroud)

我尝试用正则表达式来理解它

In [6]: re.findall(r'topics/(?P<topic_id>\d+)/$', "topics/1/")
Out[6]: ['1']
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试

In [7]: re.findall(r'topics/(?P<topic_id>\d+)/$', "topics/1/").topic_id
AttributeError: 'list' object has no attribute 'topic_id'
Run Code Online (Sandbox Code Playgroud)

似乎整数没有存储topic_id,如何理解呢?

seu*_*ing 5

你的错误不是来自'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'
Run Code Online (Sandbox Code Playgroud)