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 ...

Get The Python Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.