Lesson 02
re Functions — findall, search, finditer, and sub
Search Python text with findall, search, and finditer, then read group(), start(), and end(), or replace the match with sub.
findall collects text. search stops at the first hit. finditer walks every hit and can tell you where it sat. sub replaces what matched.
Use the playground at the bottom of this page, then take the quiz.
What you will learn
re.findall,re.search, andre.finditergroup,start, andendon a match- What
Nonemeans re.subfor replacement
The picture
Import re, then pass the pattern and the text.
| Call | Returns | Indexes? |
|---|---|---|
re.findall(pattern, text) |
A list of the matched strings | No |
re.search(pattern, text) |
The first match, or None |
Yes, on that match |
re.finditer(pattern, text) |
An iterator of match objects | Yes, on every match |
re.sub(pattern, replacement, text) |
A new string | No |
search does not continue after the first success. If nothing matches, the result is None, and calling group() on it raises AttributeError. Test for None first.
On a match object:
| Method | Meaning |
|---|---|
group() |
The matched text |
start() |
The index where the match begins |
end() |
The index just after the match |
start and end are methods of the match, not separate searches. finditer is how you get those indexes for every match. findall is enough when you only want the words or numbers themselves.
sub replaces each match with the text you choose. The original string stays as it was. You get a new one.
Example
import re
text = "Avery Lane scored 18 and 7"
print(re.findall(r"\d+", text))
found = re.search(r"\d+", text)
if found:
print(found.group(), found.start(), found.end())
for m in re.finditer(r"\d+", text):
print(m.group(), m.start(), m.end())
print(re.sub(r"\d+", "00", text))findall prints both numbers and nothing else. search prints only 18 and its indexes. The loop prints 18 and 7. sub returns the sentence with each number replaced by 00.
Key takeaways
-
findallreturns a list of strings -
searchreturns the first match orNone -
finditeryields a match for every hit -
group,start, andendread one match -
subbuilds a new string with replacements -
Next: Character Classes — brackets that choose which characters count
-
Previous: Regular Expressions
Loading playground…
Check your understanding
re functions quiz
re.findall returns:
1 / 10