Skip to Content
The Python Book
book

The Python Book

by Rob Mastrodomenico
January 2022
Beginner to intermediate
272 pages
6h 51m
English
Wiley
Content preview from The Python Book

13Regular Expressions

An extension to dealing with strings is the concept of regular expressions. The broad concept is that we can do advanced searches beyond the simple ones.

image

To do this, we will use the package re from the standard Python library and as opposed to going through all the specifics let's just jump in with some examples.

The first example looks at finding all the characters a to m within the string Rob Mastrodomenico. Now to do this we pass a string containing a‐m within list parenthesis and pass this into the findall method with the string of interest which has been called name. The result from this is a list containing all the characters in a‐m which appear in the string.

image

Next, we see how we can find the integer values 0–9 within a sequence. We can do this in two ways; the first is by mimicking what we used in the previous example with the list convention but also by using d which gives us all values that are between 0 and 9. Both return a list of values that occur within the string. Now in the first example we can see that we get back each value but what if the value was repeated? In the next example, we see that repeated values are returned in the list as we had two instances of three within the string.

This approach to finding if a value or values are ...

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

The Quick Python Book, Third Edition

The Quick Python Book, Third Edition

Naomi Ceder, David Fugate
Serious Python

Serious Python

Julien Danjou

Publisher Resources

ISBN: 9781119573319Purchase Link