Get The Learn to Code Course Bundle!
Enroll in The Complete Python Course on Udemy!
In this tutorial we are going to learn how to import different modules into a Python script. So, what is a module? A module is an external library that you can include and use in your project, without having to write the additional functionality yourself. Let’s import the regex library.
Re is included with Python, so there’s nothing that we need to install in order to use it. Regex is basically a mini-programming language that you can use within most other languages. Regex gives us a way to match certain characters and then do something based on that. Let’s cover some basic re usage.
string = "'I AM NOT YELLING', she said. Though we knew it to not be true."
This particular string has capital letters, lower-case letters, a comma, a period, and quotations. Let’s play around with this a bit.
new = re.sub('[A-Z]', '', string)
What we’re going here is instantiating the re object that we imported at the top of the script, and we’re calling the sub, or substitute, function on the re object. So just like calling any other function, we need to provide parameters to the object. We haven’t discussed classes or objects yet, and we will get to them later, but this is what we need to know for the sake of this video. The three parameters that this substitute function will take is the matches we want to make, what we want to replace them with, and then string that we’re going to manipulate. Take note that rules in regex are contained within square brackets.
As you can see, we took the capital letters A-Z and replaced them with blank space. There are all sorts of different applications for regex, and we will be using it when creating a calculator in the next video.