Skip to Content
Python in a Nutshell
book

Python in a Nutshell

by Alex Martelli
March 2003
Intermediate to advanced
656 pages
39h 30m
English
O'Reilly Media, Inc.
Content preview from Python in a Nutshell

Name

findall

Synopsis

                        r.findall(s)

When r has no groups, findall returns a list of strings, each a substring of s that is a non-overlapping match with r. For example, here’s how to print out all words in a file, one per line:

import re
reword = re.compile(r'\w+')
for aword in reword.findall(open('afile.txt').read( )):
    print aword

When r has one group, findall also returns a list of strings, but each is the substring of s matching r’s group. For example, if you want to print only words that are followed by whitespace (not punctuation), you need to change only one statement in the previous example:

reword = re.compile('(\w+)\s')

When r has n groups (where n is greater than 1), findall returns a list of tuples, one per non-overlapping match with r. Each tuple has n items, one per group of r, the substring of s matching the group. For example, here’s how to print the first and last word of each line that has at least two words:

import re
first_last = re.compile(r'^\W*(\w+)\b.*\b(\w+)\W*$', 
                                      re.MULTILINE)
for first, last in \
first_last.findall(open('afile.txt').read( )):
    print first, last
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python in a Nutshell, 3rd Edition

Python in a Nutshell, 3rd Edition

Alex Martelli, Anna Ravenscroft, Steve Holden
Python in a Nutshell, 4th Edition

Python in a Nutshell, 4th Edition

Alex Martelli, Anna Martelli Ravenscroft, Steve Holden, Paul McGuire
Data Wrangling with Python

Data Wrangling with Python

Jacqueline Kazil, Katharine Jarmul

Publisher Resources

ISBN: 0596001886Supplemental ContentCatalog PageErrata