PY Mod 3
PY Mod 3
Object-Oriented Programming (OOP) is a programming paradigm that is based on the concept of "objects."
It provides a powerful and organized way to design and structure software by modeling real-world entities
and their interactions. OOP is widely used in modern software development and is supported by many
programming languages, including Java, C++, Python, and C#.
• Modularity: OOP promotes the division of software into smaller, more manageable modules
(classes), making it easier to design, understand, and maintain complex systems.
• Reusability: OOP encourages code reuse through inheritance and composition, reducing
redundancy and saving development time.
• Maintainability: OOP makes it easier to update and extend software because changes made to a
class or object do not necessarily impact the entire system.
• Encapsulation: By encapsulating data and behavior within classes, OOP enhances data security and
reduces the risk of unintended interference.
• Flexibility: OOP allows for a flexible and extensible codebase, enabling developers to adapt to
changing requirements.
• Real-World Modeling: OOP facilitates the mapping of real-world concepts and relationships into
software, which can make the system more intuitive for developers and users.
In Python, object-oriented Programming (OOPs) is a programming paradigm that uses objects and classes
in programming. It aims to implement real-world entities like inheritance, polymorphisms, encapsulation,
etc. in the programming. The main concept of OOPs is to bind the data and the functions that work on that
together as a single unit so that no other part of the code can access this data.
A class in C++/Java/Python is the building block that leads to object-oriented programming. It is an user
defined data-type which has data members and member functions. Data members are the data variables
and member functions are the functions used to manipulate these variables. A class is defined in python
using the keyword class followed by name of the class.
An object is an instance of a class. When a class is defined, no memory is allocated but when it is instantiated
(i.e. an object is created) then the memory is allocated.
The __init__() function in the class is executed automatically every time the class is being used to create a
new object. It is called as a constructor in object oriented terminology. This function is used to initialize the
data members of the class.
In most of the object-oriented programming (OOP) languages access specifiers are used to limit the access
to the variables and functions of a class. Most of the OOP languages use three types of access specifiers, they
are: private, public and protected. In Python, all the variables and member functions of a class are public by
default. Adding a prefix __ (double underscore) to the member variable or function makes them to be
private.
CLASS
• A class will have attributes and methods.
• A Class is like an object constructor, or a "blueprint" for creating objects.
• The key word is “class”
Syntax
class class_name:
statement(s);
OBJECT
• An object is an instance of class.
• A class may have any number of objects.
• Objects can pass message between them.
Syntax
object_name = class_name(parameters);
Attributes
• Attributes are the identifiers which can hold the data.
• These attributes are used inside the class methods.
• A class may have any number of attributes.
METHODS
• Methods are nothing but functions which can do some work.
• Methods will accept parameters as input and if required return the output
• Methods can be identified by paranthesis
Example
Create a class named Person, use the __init__() function to assign values for name and age.
The __init__() method will be called automatically every time the class is being used to create a new object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
INITIALISATION USING SELF
The self in keyword in Python is used to all the instances in a class. By using the self keyword, one can
easily access all the instances defined within a class, including its methods and attributes.
__init__ is one of the reserved methods in Python. In object oriented programming, it is known as a
constructor. The __init__ method can be called when an object is created from the class, and access is
required to initialize the attributes of the class.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
The __init__() function is called automatically every time the class is being used to create a new object.
The __str__() function controls what should be returned when the class object is represented as a string.
If the __str__() function is not set, the string representation of the object is returned:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1)
Output : <__main__.Person object at 0x15039e602100>
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
Output : John(36)
Objects can also contain methods. Methods in objects are functions that belong to the object.
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Destructor method __del__()
The __del__() method is a known as a destructor method. In Python, the destructor is entirely automatic and
never called manually. It is called when an object is garbage collected which happens after all references to
the object have been deleted. The garbage collector in Python manages memory automatically. for instance,
when an object is no longer relevant, it clears the memory.
In a simple case this could be right after you delete a variable like del x or, if x is a local variable, after the
function ends. In particular, unless there are circular references, CPython which is the standard Python
implementation will garbage collect immediately.
The only property of Python garbage collection is that it happens after all references have been deleted, so
this might not necessarily happen right after and even might not happen at all.
In Python, a destructor is defined using the specific function __del__(). For instance, when we run del object
name, the object's destructor is automatically called, and it then gets garbage collected.
Example :
# create an object
Object = Myclass();
# deleting the object
del Object;
Modify Object Properties
p1.age = 40
Delete Objects
Class definitions cannot be empty, but if you for some reason have a class definition with no content, put in
the pass statement to avoid getting an error.
class Person:
pass
CLASS DEFINITION & INHERITANCE
The class statement creates a new class definition. The name of the class immediately follows the keyword
class followed by a colon as follows.
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
• The variable empCount is a class variable whose value is shared among all instances of a this class.
This can be accessed as Employee.empCount from inside the class or outside the class.
• The first method __init__() is a special method, which is called class constructor or initialization
method that Python calls when you create a new instance of this class.
• You declare other class methods like normal functions with the exception that the first argument to
each method is self. Python adds the self argument to the list for you; you do not need to include it
when you call the methods.
To create instances of a class, you call the class using class name and pass in whatever arguments its __init__
method accepts.
You access the object's attributes using the dot operator with object. Class variable would be accessed using
class name as follows.
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
Encapsulation in Python
Encapsulation is one of the key concepts of object-oriented languages like Python, Java, etc. Encapsulation
is used to restrict access to methods and variables. In encapsulation, code and data are wrapped together
within a single unit from being modified by accident.
Encapsulation is a mechanism of wrapping the data (variables) and code acting on the data (methods)
together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can
be accessed only through the methods of their current class.
Another example of Encapsulation can be a class because a class combines data and methods into a single
unit. Here, the custom function demofunc() displays the records of students wherein we can access public
data member. Using the objects st1, st2, st3, st4, we have access ed the public methods of the
class demofunc() –
class Students:
def __init__(self, name, rank, points):
self.name = name
self.rank = rank
self.points = points
# custom function
def demofunc(self):
print("I am "+self.name)
print("I got Rank ",+self.rank)
# create 4 objects
st1 = Students("Steve", 1, 100)
st2 = Students("Chris", 2, 90)
st3 = Students("Mark", 3, 76)
st4 = Students("Kate", 4, 60)
# call the functions using the objects created above
st1.demofunc()
st2.demofunc()
st3.demofunc()
st4.demofunc()
Data hiding is a part of object-oriented programming, which is generally used to hide the data information
from the user. It includes internal object details such as data members, internal working. It maintained the
data integrity and restricted access to the class member. The main working of data hiding is that it combines
the data and functions into a single unit to conceal data within a class. We cannot directly access the data
from outside the class.
Python is the most popular programming language as it applies in every technical domain and has a
straightforward syntax and vast libraries. In the official Python documentation, Data hiding isolates the
client from a part of program implementation. Some of the essential members must be hidden from the
user. Programs or modules only reflected how we could use them, but users cannot be familiar with how
the application works. Thus it provides security and avoiding dependency as well.
We can perform data hiding in Python using the __ double underscore before prefix. This makes the class
members private and inaccessible to the other classes.
Access modifiers are used by object oriented programming languages like C++,java,python etc. to restrict
the access of the class member variable and methods from outside the class. Encapsulation is an OOPs
principle which protects the internal data of the class using Access modifiers like Public,Private and
Protected.
Python supports three types of access modifiers which are public,private and protected. These access
modifiers provide restrictions on the access of member variables and methods of the class from any object
outside the class.
By default the member variables and methods are public which means they can be accessed from anywhere
outside or inside the class. No public keyword is required to make the class or methods and properties
public.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print("Name:", self.name)
print("Age:", self.age)
s = Student("John", 20)
s.display()
Class properties and methods with private access modifier can only be accessed within the class where they
are defined and cannot be accessed outside the class. In Python private properties and methods are
declared by adding a prefix with two underscores(‘__’) before their declaration.
Example : The Class BankAccount is being declared with two private variables i.e account_number and
balance and a private property display_balance which prints the balance of the bank account. As both the
properties and method are private so while accessing them from outside the class it raises Attribute error.
class BankAccount:
def __init__(self, account_number, balance):
self.__account_number = account_number
self.__balance = balance
def __display_balance(self):
print("Balance:", self.__balance)
b = BankAccount(1234567890, 5000)
b.__display_balance()
Class properties and methods with protected access modifier can be accessed within the class and from the
class that inherits the protected class. In python, protected members and methods are declared using single
underscore(‘_’) as prefix before their names.
Example : The Person class has two protected properties i.e _name and _age and a protected method
_display that displays the values of the properties of the person class. The student class is inherited from
Person class with an additional property i.e _roll_number which is also protected and a public method
display that class the _display method of the parent class i.e Person class by creating an instance of the
Student class we can call the display method from outside the class as the display method is private which
calls the protected _display method of Person class.
class Person:
def __init__(self, name, age):
8 Naipunnya School of Management, Cherthala [Jithin Babu]
BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [3]
self._name = name
self._age = age
def _display(self):
print("Name:", self._name)
print("Age:", self._age)
class Student(Person):
def __init__(self, name, age, roll_number):
super().__init__(name, age)
self._roll_number = roll_number
def display(self):
self._display()
print("Roll Number:", self._roll_number)
INHERITANCE:
Inheritance is a mechanism in which one class (derived class) acquires the property of another class (base
class). With inheritance, we can reuse the variables and methods of the existing class. The existing class is
called base class and the new class is called derived class. Hence, inheritance facilitates reusability and is
an important concept of object oriented programming. Types of inheritance are: single inheritance, multiple
inheritance, multi-level inheritance, hierarchical inheritance and hybrid inheritance.
Single inheritance enables a derived class to use the variables and functions defined in an existing class. In
multiple inheritance, derived class inherits the characteristics and features from more than one existing
classes.
In python, syntax for defining single inheritance is class z(x), where x is the name of the base class and z is
the name of the derived class. Similarly, multiple inheritance is defined using the syntax class z(x, y), where
x and y are the names of base classes and z is the name of the derived class.
Advantages of inheritance
Inheritance is the capability of one class to derive or inherit the properties from some another class. The
benefits of inheritance are:
Example :
# person is a base class
class person:
def __init__(self, n, a):
self.name = n
self.age = a
# employee is the class derived from person using single inheritance
class employee(person):
def __init__(self, n,a, d,s):
person.__init__(self,n,a)
self.designation=d
self.salary=s
def show(self):
print("Employee Details: ")
print(" Name: ",self.name,"\n Age:",self.age, "\n Designation:",self.designation, "\n
Salary:",self.salary)
# student is a base class
class student:
def __init__(self, id, rno):
self.studentId = id
self.roomno=rno
# resident is a class derived from person and student using multiple inheritance
class resident(person, student):
def __init__(self, n, a, id,rno):
person.__init__(self, n, a)
student.__init__(self, id,rno)
def show(self):
print("Resident Details:")
print(" Name:", self.name,"\n Age: ",self.age, "\n Id:" ,self.studentId,"\n Room no.:",self.roomno)
# Creating objects of employee and resident classes
e1 =employee("Arun",35,"Data analyst",50000)
r1 = resident("John", 30, 201900025,203)
e1.show()
r1.show()
Result:
Employee Details:
Name: Arun
Age: 35
Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads to the
termination of the program.
Exceptions: Exceptions are raised when the program is syntactically correct, but the code results in an
error. This error does not stop the execution of the program, however, it changes the normal flow of the
program.
If you have some suspicious code that may raise an exception, you can defend your program by placing the
suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code
which handles the problem as elegantly as possible.
• The try: block contains statements which are susceptible for exception
• If exception occurs, the program jumps to the except: block.
• If no exception in the try: block, the except: block is skipped.
Syntax
try:
You do your operations here
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Example: Let us try to access the array element whose index is out of bound and handle the corresponding
exception.
a = [1, 2, 3]
try:
except:
In the above example, the statements that can cause the error are placed inside the try statement (second
print statement in our case). The second print statement tries to access the fourth element of the list which
is not there and this throws an exception. This exception is then caught by the except statement.
Exception is the base class for all the exceptions in Python. A single try statement can have multiple except
statements. This is useful when the try block contains statements that may throw different types of
exceptions.
You can also provide a generic except clause, which handles any exception.
After the except clause(s), you can include an else clause. The code in the else block executes if the code in
the try: block does not raise an exception.
The else block is a good place for code that does not need the try: block's protection.
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
fh.close()
You can also use the except statement with no exceptions defined as follows
try:
You do your operations here
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
This kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except
statement is not considered a good programming practice though, because it catches all exceptions but does
not make the programmer identify the root cause of the problem that may occur.
You can also use the same except statement to handle multiple exceptions as follows
try:
You do your operations here
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
12 Naipunnya School of Management, Cherthala [Jithin Babu]
BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [3]
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
You can provide except clause(s), or a finally clause, but not both. You cannot use else clause as well along
with a finally clause.
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print ("Error: can\'t find file or read data")
fh.close()
In Python, there are several built-in exceptions that can be raised when an error occurs during the execution
of a program. Here are some of the most common types of exceptions in Python:
• SyntaxError: This exception is raised when the interpreter encounters a syntax error in the code,
such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.
• TypeError: This exception is raised when an operation or function is applied to an object of the
wrong type, such as adding a string to an integer.
• NameError: This exception is raised when a variable or function name is not found in the current
scope.
• IndexError: This exception is raised when an index is out of range for a list, tuple, or other sequence
types.
• KeyError: This exception is raised when a key is not found in a dictionary.
• ValueError: This exception is raised when a function or method is called with an invalid argument
or input, such as trying to convert a string to an integer when the string does not represent a valid
integer.
• AttributeError: This exception is raised when an attribute or method is not found on an object, such
as trying to access a non-existent attribute of a class instance.
• IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails due
to an input/output error.
• ZeroDivisionError: This exception is raised when an attempt is made to divide a number by zero.
• ImportError: This exception is raised when an import statement fails to find or load a module.
These are just a few examples of the many types of exceptions that can occur in Python.
try:
You do your operations here
......................
except ExceptionType as Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable follow the name of the exception
in the except statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of
the exception.
This variable receives the value of the exception mostly containing the cause of the exception. The variable
can receive a single value or multiple values in the form of a tuple. This tuple usually contains the error
string, the error number, and an error location.
temp_convert("xyz")
It will produce the following output −
You can raise exceptions in several ways by using the raise statement. The general syntax for the raise
statement is as follows –
Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception
argument. The argument is optional; if not supplied, the exception argument is None.
The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback
object used for the exception.
Example
An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are
classes, with an argument that is an instance of the class. Defining new exceptions is quite easy and can be
done as follows −
try:
Business Logic here...
except Exception as e:
Exception handling here using e.args...
else:
Rest of the code here...
The following example illustrates the use of raising an exception −
try:
l=functionName(-10)
print ("level=",l)
except Exception as e:
print ("error in level argument",e.args[0])
This will produce the following output −
User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes from the standard built-in
exceptions.
Here is an example that has a user-defined MyException class. Here, a class is created that is subclassed
from base Exception class. This is useful when you need to display more specific information when an
exception is caught.
In the try block, the user-defined exception is raised whenever value of num variable is less than 0 or more
than 100 and caught in the except block. The variable e is used to create an instance of the class
MyException.
Example
class MyException(Exception):
def __init__(self):
print("Object created...")
num = 110
try:
if num <0 or num>100:
raise MyException
except MyException as e:
print ("Invalid marks:", num)
else:
print ("Marks obtained:", num)
Assertions in Python
Python Assertions are the debugging tools that help in the smooth flow of code. Assertions are mainly
assumptions that a programmer knows or always wants to be true and hence puts them in code so that
failure of these doesn’t allow the code to execute further.
In simpler terms, we can say that assertion is the boolean expression that checks if the statement is True or
False. If the statement is true then it does nothing and continues the execution, but if the statement is False
then it stops the execution of the program and throws an error.
In Python, the assert keyword helps in achieving this task. This statement takes as input a boolean
condition, which when returns true doesn’t do anything and continues the normal flow of execution, but if
it is computed to be false, then it raises an AssertionError along with the optional message provided.
Parameters:
When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully
true. If the expression is false, Python raises an AssertionError exception.
# initializing number
a=4
b=0
# using assert to check for 0
print("The value of a / b is : ")
assert b != 0, “Enter a positive number”
print(a / b)
Output:
The value of a / b is :
Traceback (most recent call last):
File "/home/cg/root/20097/main.py", line 9, in <module>
assert b != 0, "Enter a positive number"
AssertionError: Enter a positive number
If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError.
AssertionError exceptions can be caught and handled like any other exception using the try-except
statement, but if not handled, they will terminate the program and produce a traceback.
The assert statement is used inside a function in this example to verify that a rectangle’s length and width
are positive before computing its area. The assertion raises an AssertionError with the message “Length
and width must be positive” if it is false. If the assertion is true, the function returns the rectangle’s area; if
it is false, it exits with an error. To show how to utilize assert in various situations, the function is called
twice, once with positive inputs and once with negative inputs.
# Return statement
return area
# Calling the function with positive inputs
area1 = calculate_rectangle_area(5, 6)
print("Area of rectangle with length 5 and width 6 is", area1)
# Calling the function with negative inputs
area2 = calculate_rectangle_area(-5, 6)
print("Area of rectangle with length -5 and width 6 is", area2)
Output:
Area of rectangle with length 5 and width 6 is 30
Traceback (most recent call last):
File "/home/cg/root/40203/main.py", line 18, in <module>
area2 = calculate_rectangle_area(-5, 6)
File "/home/cg/root/40203/main.py", line 6, in calculate_rectangle_area
assert length > 0 and width > 0, "Length and width must be positive"
AssertionError: Length and width must be positive
Example
# Initializing variables
a = "hello"
b = 42
# Asserting the type of a variable
assert type(a) == str
assert type(b) == int
# Printing the values of a and b
print("a =", a)
print("b =", b)
Example
# Initializing a dictionary
my_dict = {"apple": 1, "banana": 2, "cherry": 3}
# Asserting the contents of the dictionary
assert my_dict["apple"] == 1
assert my_dict["banana"] == 2
assert my_dict["cherry"] == 3
# Printing the dictionary
print("My dictionary contains the following key-value pairs:", my_dict)
Example
# Python 3 code to demonstrate working of assert Application
# initializing list of foods temperatures
batch = [ 40, 26, 39, 30, 25, 21]
Assumptions made by your code can be verified with the assert statement. You may rapidly find mistakes
and debug your program by placing assert statements throughout your code. Assert statements make it
simpler for others to understand and work with your code since they explicitly describe the assumptions
that your code is making. In order to ensure that certain requirements are met, assert statements are
frequently used in unit testing. You can make sure that your code is working properly and that any changes
you make don’t damage current functionality by incorporating assert statements in your tests. And you can
use assert to check that program inputs comply with requirements and validate them. By doing so, security
flaws like buffer overflows and SQL injection attacks may be avoided.
Regular Expressions
A regular expression is a special sequence of characters that helps you match or find other strings or sets
of strings, using a specialized syntax held in a pattern. A regular expression also known as regex is a
sequence of characters that defines a search pattern. It is a sequence of characters that specifies a match
pattern in text. Usually, such patterns are used by string-searching algorithms for "find" or "find and
replace" operations on strings, or for input validation.
Large scale text processing in data science projects requires manipulation of textual data. Python's standard
library has 're' module for this purpose.
Regular expressions use the backslash character ('\') to indicate special forms or to allow special characters
to be used without invoking their special meaning. Python on the other hand uses the same character as
escape character. Hence Python uses the raw string notation.
A string become a raw string if it is prefixed with r or R before the quotation symbols. Hence 'Hello' is a
normal string were are r'Hello' is a raw string.
>>> normal="Hello"
>>> print (normal)
Hello
>>> raw=r"Hello"
>>> print (raw)
Hello
In normal circumstances, there is no difference between the two. However, when the escape character is
embedded in the string, the normal string actually interprets the escape sequence, where as the raw string
doesn't process the escape character.
>>> normal="Hello\nWorld"
This Python code uses regular expressions to search for the word “portal” in the given string and then
prints the start and end indices of the matched word within the string.
import re
s = "The quick brown. fox jumps over the lazy dog"
match = re.search(r'brown', s)
print('Start Index:', match.start())
print('End Index:', match.end())
Before starting with the Python regex module let’s see how to actually write regex using metacharacters or
special sequences.
MetaCharacters
To understand the RE analogy, MetaCharacters are useful, important, and will be used in functions of
module re. Below is the list of metacharacters.
above table). So for this case, we will use the backslash(\) just before the dot(.) so that it will lose its
specialty.
import re
s = "The quick brown. fox jumps over the lazy dog"
# without using \
match = re.search(r'.', s)
print(match)
# using \
match = re.search(r'\.', s)
print(match)
[] – Square Brackets represent a character class consisting of a set of characters that we wish to match.
For example, the character class [abc] will match any single a, b, or c.
We can also specify a range of characters using – inside the square brackets. For example,
We can also invert the character class using the caret(^) symbol. For example,
Example:
In this code, you’re using regular expressions to find all the characters in the string that fall within the range
of ‘a’ to ‘m’. The re.findall() function returns a list of all such characters. In the given string, the characters
that match this pattern are: ‘c’, ‘k’, ‘b’, ‘f’, ‘j’, ‘e’, ‘h’, ‘l’, ‘d’, ‘g’.
import re
string = "The quick brown fox jumps over the lazy dog"
pattern = "[a-m]"
result = re.findall(pattern, string)
print(result)
^ – Caret
Caret (^) symbol matches the beginning of the string i.e. checks whether the string starts with the given
character(s) or not. For example –
^g will check if the string starts with g such as good, globe, girl, g, etc.
^go will check if the string starts with go such as good, goat, etc.
Example: This code uses regular expressions to check if a list of strings starts with “The”. If a string begins
with “The,” it’s marked as “Matched” otherwise, it’s labeled as “Not matched”.
21 Naipunnya School of Management, Cherthala [Jithin Babu]
BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [3]
import re
regex = r'^The'
strings = ['The quick brown fox', 'The lazy dog', 'A quick brown fox']
for string in strings:
if re.match(regex, string):
print(f'Matched: {string}')
else:
print(f'Not matched: {string}')
$ – Dollar
Dollar($) symbol matches the end of the string i.e checks whether the string ends with the given
character(s) or not. For example –
s$ will check for the string that ends with a such as looks, ends, s, etc.
ks$ will check for the string that ends with ks such as looks, ks, etc.
Example: This code uses a regular expression to check if the string ends with “World!”. If a match is found,
it prints “Match found!” otherwise, it prints “Match not found”.
import re
string = "Hello World!"
pattern = r"World!$"
match = re.search(pattern, string)
if match:
print("Match found!")
else:
print("Match not found.")
. – Dot
Dot(.) symbol matches only a single character except for the newline character (\n). For example –
a.b will check for the string that contains any character at the place of the dot such as acb, acbd, abbb, etc
Example: This code uses a regular expression to search for the pattern “brown.fox” within the string. The
dot (.) in the pattern represents any character. If a match is found, it prints “Match found!” otherwise, it
prints “Match not found”.
import re
string = "The quick brown fox jumps over the lazy dog."
pattern = r"brown.fox"
match = re.search(pattern, string)
if match:
print("Match found!")
22 Naipunnya School of Management, Cherthala [Jithin Babu]
BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [3]
else:
print("Match not found.")
Special Sequences
Special sequences do not match for the actual character in the string instead it tells the specific location in
the search string where the match must occur. It makes it easier to write commonly used patterns.
[..] : Matches any single character in a square bracket and [^..] matches any single character not in square
bracket.
\ : It is used for special meaning characters like \. to match a period or \+ for plus sign.
a| b : Matches either a or b
re.match() Function
This function attempts to match RE pattern at the start of string with optional flags.
String : This is the string, which would be searched to match the pattern at the beginning of string.
Flags : You can specify different flags using bitwise OR (|). These are modifiers, which are listed in the table
below.
The re.match function returns a match object on success, None on failure. A match object instance contains
information about the match: where it starts and ends, the substring it matched, etc.
The match object's start() method returns the starting position of pattern in the string, and end() returns
the endpoint.
Example
import re
line = "Cats are smarter than dogs"
matchObj = re.match( r'Cats', line)
print (matchObj.start(), matchObj.end())
print ("matchObj.group() : ", matchObj.group()
re.search() Function
This function searches for first occurrence of RE pattern within the string, with optional flags.
String : This is the string, which would be searched to match the pattern anywhere in the string.
Flags : You can specify different flags using bitwise OR (|). These are modifiers, which are listed in the table
below.
import re
line = "Cats are smarter than dogs"
matchObj = re.search( r'than', line)
print (matchObj.start(), matchObj.end())
print ("matchObj.group() : ", matchObj.group())
Python offers two different primitive operations based on regular expressions : match checks for a match
only at the beginning of the string, while search checks for a match anywhere in the string.
re.findall()
Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-
right, and matches are returned in the order found.
Example : This code uses a regular expression (\d+) to find all the sequences of one or more digits in the
given string. It searches for numeric values and stores them in a list. In this example, it finds and prints the
numbers “123456789” and “987654321” from the input string.
import re
string = "Hello my Number is 123456789 and my friend's number is 987654321"
regex = '\d+'
match = re.findall(regex, string)
print(match)
re.sub() Function
One of the most important re methods that use regular expressions is sub.
Example
import re
#Replace all white-space characters with the digit "9":
txt = "The rain in Spain"
x = re.sub("\s", "9", txt)
print(x)
You can control the number of replacements by specifying the count parameter:
Example
import re
# Replace the first 2 occurrences:
txt = "The rain in Spain"
x = re.sub("\s", "9", txt, 2)
print(x)