How to Use findall in Python: Syntax and Examples
Use
re.findall(pattern, string) to find all non-overlapping matches of pattern in string. It returns a list of all matches found as strings or tuples if groups are used.Syntax
The re.findall() function has this syntax:
pattern: The regular expression pattern to search for.string: The text where you want to find matches.- Returns a list of all matches found in the string.
python
import re
matches = re.findall(pattern, string)Example
This example finds all words that start with a capital letter in a sentence.
python
import re text = "Hello World! This is a Test." matches = re.findall(r"\b[A-Z][a-z]*\b", text) print(matches)
Output
['Hello', 'World', 'This', 'Test']
Common Pitfalls
One common mistake is using re.findall() with groups in the pattern, which returns tuples instead of strings. Also, forgetting to import re causes errors.
Another pitfall is expecting overlapping matches, but findall only finds non-overlapping matches.
python
import re text = "abc123def456" # Wrong: pattern with groups returns tuples matches_wrong = re.findall(r"(\d)(\d)(\d)", text) print(matches_wrong) # Right: pattern without groups returns strings matches_right = re.findall(r"\d{3}", text) print(matches_right)
Output
[('1', '2', '3'), ('4', '5', '6')]
['123', '456']
Quick Reference
- re.findall(pattern, string): Returns all matches as a list.
- Use raw strings (prefix
r) for patterns to avoid escape issues. - Groups in pattern return tuples of groups per match.
- Matches are non-overlapping.
Key Takeaways
Use re.findall() to get all matches of a pattern in a string as a list.
Patterns with groups return tuples for each match; without groups, they return strings.
Always import the re module before using findall.
Use raw strings (r"pattern") to write regex patterns safely.
findall finds non-overlapping matches only.