I need to restrict re.findall to find the first 3 matches and then stop.
eg
text = 'some1 text2 bla3 regex4 python5' re.findall(r'\d',text)
then I get:
['1', '2', '3', '4', '5']
I want too:
['1', '2', '3']
To find N matches and stop, you can use re.finditer and itertools.islice :
>>> import itertools as IT >>> [item.group() for item in IT.islice(re.finditer(r'\d', text), 3)] ['1', '2', '3']
re.findall returns a list, so the easiest solution would be to simply use slicing :
re.findall
>>> import re >>> text = 'some1 text2 bla3 regex4 python5' >>> re.findall(r'\d', text)[:3] # Get the first 3 items ['1', '2', '3'] >>>