Python regular expressions (tutorial)

#!/usr/bin/python3.3

#Regeex used the re library
import re

def main():
#search(“Ishaan”)
#exceptions()
#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 re.search function to check if the word exists or not in the line
if re.search(k,line):
print(line)
fh1 =open(‘1.txt’)
for line1 in fh1:
match = re.search(k,line1)
if match:
print(match.group())
#Replacing a word with another
fh2 = open(‘1.txt’)
for line in fh2:
print(re.sub(k,’ishaan1′,line))

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

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

#How to railse an exceptiom

#Function without any statements use pass

def noStatementFunc():
pass

#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):
print(kwargs[‘one’],kwargs[‘two’])
#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()

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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