任何人都可以解釋爲什麼打印match.group()只返回結果匹配第一次在for循環中調用下面?我希望它在每次調用時打印匹配。我遇到過這種例子在Python文檔經歷this section同時:正則表達式HOWTO爲什麼Python重新finditer()group()屬性只在解釋器中首次調用時返回匹配項?
Python 2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> p = re.compile('\d+')
>>> iterator = p.finditer('12 drummers, 11 pipers, 10 dancers')
>>> iterator
<callable-iterator object at 0x107deabd0>
>>> for match in iterator:
... print match.group()
...
12
11
10
>>> for match in iterator:
... print match.group()
...
>>>
如果您反覆使用這些匹配,可能使用re.findall:>>> import re >>> p = re.compile('\ d +') >>> mylist = p。的findall('12鼓手,11個風笛,10名舞者 ') >>>打印MYLIST [' 12' , '11', '10'] >>> – rtrwalker
@rtrwalker,這是一個很好的建議。 –