re.findall()

What You'll Learn: In this tutorial, you'll discover how to use the re.findall() function to find all non-overlapping matches of a pattern in a string. This function returns all the findings as a list.

Syntax

The syntax of the re.findall() function is:

python
re.findall(pattern, string, flags=0)

Parameters

  • pattern (required): The pattern to be found in the string.
  • string (required): The string in which the pattern is to be found.
  • flags (optional): Optional flags like re.IGNORECASE.

Return Value

The function returns a list of matches.

Examples

  1. Finding Substring in a String
    • Example Code:

      python
      import re
      pattern = 'abc'
      string = 'abcdefabcab'
      result = re.findall(pattern, string)
      print(result)
      
    • Output:

       
      ['abc', 'abc']
      
  2. Finding Pattern in a String
    • Example Code:

      python
      import re
      pattern = '[a-z]+'
      string = 'abc---cab-efg_web'
      result = re.findall(pattern, string)
      print(result)
      
    • Output:

       
      ['abc', 'cab', 'efg', 'web']
      
  3. Non-Overlapping Occurrences
    • Example Code:

      python
      import re
      pattern = 'aba'
      string = 'ababaiiaba'
      result = re.findall(pattern, string)
      print(result)
      
    • Output:

       
      ['aba', 'aba']
      
  4. Using Flags
    • Example Code:

      python
      import re
      pattern = '[a-z]+'
      string = 'aBC---CAB-eFg_web'
      flags = re.IGNORECASE
      result = re.findall(pattern, string, flags)
      print(result)
      
    • Output:

       
      ['aBC', 'CAB', 'eFg', 'web']
      
    • Note: The re.IGNORECASE flag makes the function ignore case while finding matches.

Try It Yourself: Fun Exercises

  1. Find All Digits:
    • Create a string with numbers and letters.
    • Use re.findall() to find all digit patterns in the string.
  2. Match Words:
    • Write a sentence and use re.findall() to find all words that start with a specific letter.

Summary:

In this Python tutorial, we learned how to use the re.findall() function to get all non-overlapping matches for a given pattern in a string. This function is powerful for searching and extracting patterns in text. Keep experimenting and have fun with Python!