Practical11 Python Programming CkC21BUjW7
Practical11 Python Programming CkC21BUjW7
PRACTICAL 11
Part A (To be referred by students)
Theory:
Regular Expression:-
- RE are noting but strings continuing characters and special symbols.
- Also called regex
- Python provides re module for RE
- This module contains methods like
o compile()
o search()
o match()
o findall()
o split()
o sub()
etc
- Example:-
import re
reg=r'm\w\w' # r is used to represented, it is raw string.
print(reg)
o m – represents the words starting with ‘m’ should be matched
o w – represents any one character in a-a or A-Z or 0-9
1|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II
compile( ) method of re
- it’s a step after creating RE. Compile RE.
search( ) and match( )
- its step after compilation to run expression on string.
group( )
- it’s a method to access string return by search( ) or match( )
str1='systematic'
result=prog.search(str1)
print(result.group())
2|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II
str1='system'
result=prog.search(str1)
if result:
print(result.group( ))
findall( )
- This method returns all resultant string into a list.
Example:-
import re
prog=re.compile(r'm\w\w')
str='cat mat bat rat moon man'
result=prog.findall(str)
print(result)
match( )
- It returns the resultant string only if it is found in beginning of the string.
- The match( ) functions returns None if the string is not in the beginning.
Python program to create a RE using the match ( ) method to search for strings starting
with m and having total 3 characters.
Program 1:-
import re
str='man ran maaa'
result=re.match(r'm\w\w',str)
print(result.group())
Program 2:-
import re
str='ran maaa'
result=re.match(r'm\w\w',str)
print(result)
split( )
- To split the string into pieces according to RE and returns the pieces as elements of a
list.
- Example:=
3|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II
re.split(r‘\W+’,str)
o w – Represents alphanumeric characters.
o W – Represents any character that is not alphanumeric.
+ after W represents to match 1 or more occurrences indicated by W.
import re
str='This; is the: "core" python\'s book'
result=re.split(r'\W+',str)
print(result)
output:-
['This', 'is', 'the', 'core', 'python', 's', 'book']
sub( )
- Finds a string and replace it with a new string.
- Format of the method is:
re.sub(RE, new string, string)
- Example:-
re.sub(r‘Mumbai’, ‘Shirpur’, str)
4|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II
Question:- Write a program to create a RE to retrieve all words starting with ‘a’ in a
given string
import re
str='an apple a day keeps the Dr away'
result=re.findall(r'a[\w]*',str)
for s in result:
print(s)
output:-
an
apple
a
ay
away
import re
str='an apple a day keeps teh Dr away'
result=re.findall(r'\ba[\w]*\b',str)
for s in result:
print(s)
Output:-
an
apple
a
away
5|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II
Quantifiers in RE
- Some characters are used to represent more than one character to be matched in
the string.
+ 1 or more repetitions
* 0 or more reparations
? 0 or 1
{m} Exactly m occurrences
{m,n} From m to n, m default 0 and n to infinity
6|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II
SQLITE
Python has built-in support for SQLite in the form of the sqlite3 module. This module
contains functions for performing persistent CRUD operations on SQLite database.
The following command is used to install the sqlite3 package.
connect():
To establish a connection with a SQLite database, sqlite3 module needs to be imported and
the connect() function needs to be executed.
>>> db=sqlite3.connect('test.db')
The connect() function returns a connection object referring to the existing database or a
new database if it doesn't exist.
Method Description
cursor() Returns a Cursor object which uses this Connection.
commit() Explicitly commits any pending transactions to the database. The method should be a
no-op if the underlying db does not support transactions.
rollback( This optional method causes a transaction to be rolled back to the starting point. It
) may not be implemented everywhere.
close() Closes the connection to the database permanently. Attempts to use the connection
after calling this method will raise a DB-API Error.
A cursor is a Python object that enables you to work with the database. It acts as a handle
for a given SQL query; it allows the retrieval of one or more rows of the result. Hence, a
cursor object is obtained from the connection to execute SQL queries using the following
statement:
>>> cur=db.cursor()
7|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II
Method Description
execute() Executes the SQL query in a string parameter
executemany() Executes the SQL query using a set of parameters in the list of tuples
fetchone() Fetches the next row from the query result set.
fetchall() Fetches all remaining rows from the query result set.
callproc() Calls a stored procedure.
close() Closes the cursor object.
execute():
The execute() method of the cursor receives a string containing the SQL query. A string
having an incorrect SQL query raises an exception, which should be properly handled.
That's why the execute() method is placed within the try block and the effect of the SQL
query is persistently saved using the commit() method. If however, the SQL query fails,
the resulting exception is processed by the except block and the pending transaction is
undone using the rollback() method.
E:\SQLite>sqlite3 test.db
SQLite version 3.25.1 2018-09-18 20:20:44
Enter ".help" for usage hints.
sqlite> .tables
student
Insert a Record:
import sqlite3
db=sqlite3.connect('test.db')
8|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II
Retrieve Records:
1. fetchone(): Fetches the next available record from the result set. It is a tuple consisting
of values of each column of the fetched record.
2. fetchall(): Fetches all remaining records in the form of a list of tuples. Each tuple
corresponds to one record and contains values of each column in the table.
import sqlite3
db=sqlite3.connect('test.db')
sql="SELECT * from student;"
cur=db.cursor()
cur.execute(sql)
while True:
record=cur.fetchone()
if record==None:
break
print (record)
db.close()
students=cur.fetchall()
for rec in students:
print (rec)
Update a Record:
import sqlite3
db=sqlite3.connect('test.db')
qry="update student set age=? where name=?;"
try:
cur=db.cursor()
cur.execute(qry, (19,'Deepak'))
9|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II
db.commit()
print("record updated successfully")
except:
print("error in operation")
db.rollback()
db.close()
Delete a Record:
import sqlite3
db=sqlite3.connect('test.db')
qry="DELETE from student where name=?;"
try:
cur=db.cursor()
cur.execute(qry, ('Bill',))
db.commit()
print("record deleted successfully")
except:
print("error in operation")
db.rollback()
db.close()
PRACTICAL 11
Part B (to be completed by students)
10 | P a g e