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
- Finding Substring in a String
Example Code:
pythonimport re pattern = 'abc' string = 'abcdefabcab' result = re.findall(pattern, string) print(result)Output:
['abc', 'abc']
- Finding Pattern in a String
Example Code:
pythonimport re pattern = '[a-z]+' string = 'abc---cab-efg_web' result = re.findall(pattern, string) print(result)Output:
['abc', 'cab', 'efg', 'web']
- Non-Overlapping Occurrences
Example Code:
pythonimport re pattern = 'aba' string = 'ababaiiaba' result = re.findall(pattern, string) print(result)Output:
['aba', 'aba']
- Using Flags
Example Code:
pythonimport 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.IGNORECASEflag makes the function ignore case while finding matches.
Try It Yourself: Fun Exercises
- Find All Digits:
- Create a string with numbers and letters.
- Use
re.findall()to find all digit patterns in the string.
- Match Words:
- Write a sentence and use
re.findall()to find all words that start with a specific letter.
- Write a sentence and use
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!