What is the difference between re.findall() and re.finditer() methods available in Python?

PythonServer Side ProgrammingProgramming

The re.findall() method

The re.findall() helps to get a list of all matching patterns. It searches from start or end of the given string. If we use method findall to search for a pattern in a given string it will return all occurrences of the pattern. While searching a pattern, it is recommended to use re.findall() always, it works like re.search() and re.match() both.

Example

import re result = re.search(r'TP', 'TP Tutorials Point TP')

print result.group()

Output

TP

The re.finditer() method

re.finditer(pattern, string, flags=0)

 Return an iterator yielding MatchObject instances over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result. 

The following code shows the use of re.finditer() method in Python regex

Example

import re s1 = 'Blue Berries'
pattern = 'Blue Berries'
for match in re.finditer(pattern, s1):
    s = match.start()
    e = match.end()
    print 'String match "%s" at %d:%d' % (s1[s:e], s, e)

Output

Strings match "Blue Berries" at 0:12
raja
Published on 11-Jan-2018 06:12:53
Advertisements