Open a file “basics.txt” and load it into a file object variable. Read the contents of file_object into a new variable named data. Now close the file_object file so it isn’t taking up memory. Import re. Create an re.match() for the word “Four” in the data variable. Assign this to a new variable named first. # Finally, make a new variable named liberty that is an re.search() for the word “Liberty” in our data variable.
import re file_object = open('basics.txt', encoding='utf-8') data = file_object.read() file_object.close() first = re.match('Four', data) liberty = re.match('Liberty', data) last_name = r'Love' first_name = r'Kenneth' print(re.match(last_name, data)) print(re.search(first_name, data))
.open()
A method that creates a pointer to a file in Python
.read()
Copy datat from a file object to a variable
.close()
Once a file is open and you don’t need it anymore, this is how you remove it from memory.
r
A raw string starts with r
r_name = r’Bashar’
re.match()
A method to start matching a regular expression pattern against the beginning of a string.
re.search()
If you don’t know if the pattern is at the beginning of a string. Use this method so it’ll find it anywhere in the string.