The findall() function

This is one of the methods of the match object. The findall() method finds all the matches and then returns them as a list of strings. Each element of the list represents as a match. This method searches for the pattern without overlapping.

Create a re_findall_example.py script and write the following content in it:

import re

pattern = 'Red'
colors = 'Red, Blue, Black, Red, Green'
p = re.findall(pattern, colors)
print(p)

str_line = 'Peter Piper picked a peck of pickled peppers. How many pickled peppers did Peter Piper pick?'
pt = re.findall('pew+', str_line)
pt1 = re.findall('picw+', str_line)
print(pt)
print(pt1)

line = 'Hello hello HELLO bye'
p = re.findall('hew+', line, re.IGNORECASE)
print(p)

Run the script and you will get the output as follows:

student@ubuntu:~/work$ python3 re_findall_example.py
['Red', 'Red']
['per', 'peck', 'peppers', 'peppers', 'per']
['picked', 'pickled', 'pickled', 'pick']
['Hello', 'hello', 'HELLO']

In the preceding script, we have written three examples of the findall() method. In the first example, we defined a pattern and a string. We found that pattern from the string using the findall() method and then printed it. In the second example, we created a string and we found the words whose first two letters are pe using findall() and then printing them. We will get the list of words whose first two letters are pe.

In addition, we found the words whose first three letters are pic and then print them. Here, also, we will get the list of strings. In the third example, we created a string in which we specified hello in uppercase and lowercase, and a word: bye. Using findall(), we find the words whose first two letters are he. Also in findall(), we used a re.IGNORECASE flag that will ignore the case of the word and printed them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset