Skip to main content
MahiDev — Learn. Build. Become AI-ready.

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.

Intermediate25 min
re functions hero Module 18 Lesson 2 findall search finditer 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, and re.finditer
  • group, start, and end on a match
  • What None means
  • re.sub for replacement

The picture

What each call gives you back

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

python
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

  • findall returns a list of strings

  • search returns the first match or None

  • finditer yields a match for every hit

  • group, start, and end read one match

  • sub builds 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