Python regular expressions (tutorial)


#Regeex used the re library
import re

def main():
#NamedArguments(one = 1,two = 2)
for i in inRange(0,10,1):
print(i,end=” “)

def search(k=”asd”):
fh =open(‘1.txt’)
for line in fh:
#using the function to check if the word exists or not in the line
fh1 =open(‘1.txt’)
for line1 in fh1:
match =,line1)
if match:
#Replacing a word with another
fh2 = open(‘1.txt’)
for line in fh2:

#precompile Regular expressions for Efficeiency
fh3 = open(‘1.txt’)
pattern = re.compile(k, re.IGNORECASE)
for line in fh3:

#Exceptions are key method for handling errors.Catch exceptions using try catch
def exceptions():
fh = open(‘asd.txt’)
print(“no file founf”)
print(“File found. Do something with it.”)

#How to railse an exceptiom

#Function without any statements use pass

def noStatementFunc():

#Functions with non fixed number of Arguments
#here this, that are compulsory arguments and then the optional arguments
def noLimitArguments(this,that,*args):
print(this,that,args) #here args is a tuple and can use for loop to iterate

#using Named function arguments called Keyword Args and is actually a dictionary

def NamedArguments(**kwargs):
#when name of the Kargs are not known
#As kwargs is a dictionary. Will not maintain order
for k in kwargs:print(k,kwargs[k])

#Creating an Generator function
#using the yeild function instead of return
def inRange(start,stop,step):
i = start
while i <= stop:
yield i #yeild function would retun. But when the nexttime the function is called it will start from the next line to yield.
i += step

if __name__ == "__main__" : main()


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s