What is the difference between re.search() and re.findall() methods in Python regular expressions?


The re.search() method is similar to re.match() but it doesn’t limit us to find matches at the beginning of the string only. 

Example

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

Output

Tutorials

Here you can see that, search() method is able to find a pattern from any position of the string.

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


Updated on: 13-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements