RePlace with regular expressions Python 3


show more Replacing with regular expressions provides you with in-depth training on Developer. Taught by Bill Weinman as part of the Python 3 Essential Training show less
please wait ...

Replacing with regular expressions

Let's take a look at how we can do search and replace using regular expressions in Python. Start by making a working copy of regex.py. Call it regex-working.py. We'll open our working copy and here we have our little script that searches for a particular pattern in a file. If we run this, you see it finds all the places where either Lenore or Nevermore is found in Edgar Allan Poe's "The Raven." So let's do a search and replace instead of just a plain search.

Search and replace in Python is done with re.sub, so we'll change this re.search to re.sub and we'll use the same pattern there. And we put in our replacement pattern here. We'll just replace it with some hash marks and we are going to turn this if into just a print and we'll at the end of that, we'll put the end= blank like that and we don't need this anymore.

So now, we have re.sub and sub is the search and replace in the regular expression package in Python and the first argument is...

Replacing with regular expressions
Video duration: 3m 29s 6h 36m Beginner

Viewers:

Replacing with regular expressions provides you with in-depth training on Developer. Taught by Bill Weinman as part of the Python 3 Essential Training

Subjects:
Developer Web
Software:
Python
Author:
please wait ...