0% found this document useful (0 votes)
13 views69 pages

Unit 4 Python

This document covers Python data types, including Numeric, Sequence, Boolean, Set, Dictionary, and Binary types. It explains the use of the type() function to determine data types and provides examples of creating and accessing various data types such as strings, lists, and tuples. Additionally, it highlights the characteristics of each data type, including mutability and structure.

Uploaded by

priyangas100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views69 pages

Unit 4 Python

This document covers Python data types, including Numeric, Sequence, Boolean, Set, Dictionary, and Binary types. It explains the use of the type() function to determine data types and provides examples of creating and accessing various data types such as strings, lists, and tuples. Additionally, it highlights the characteristics of each data type, including mutability and structure.

Uploaded by

priyangas100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 69

PYTHON PROGRAMMING

UNIT-4
Python Data Types
Data types are the classification or categorization of data items. It represents the
kind of value that tells what operations can be performed on a particular data. Since
everything is an object in Python programming, data types are actually classes and
variables are instances (object) of these classes. The following are the standard or
built-in data types in Python:
 Numeric
 Sequence Type
 Boolean
 Set
 Dictionary
 Binary Types( memoryview, bytearray, bytes)

What is Python type() Function?

To define the values of various data types and check their data types we use
the type() function. Consider the following examples.
Python3

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
# DataType Output: str
x = "Hello World"

# DataType Output: int


x = 50

# DataType Output: float


x = 60.5

# DataType Output: complex


x = 3j

# DataType Output: list


x = ["geeks", "for", "geeks"]

# DataType Output: tuple


x = ("geeks", "for", "geeks")

# DataType Output: range


x = range(10)

# DataType Output: dict


x = {"name": "Suraj", "age": 24}

# DataType Output: set


x = {"geeks", "for", "geeks"}

# DataType Output: frozenset


x = frozenset({"geeks", "for", "geeks"})

# DataType Output: bool


x = True

# DataType Output: bytes


x = b"Geeks"

# DataType Output: bytearray


x = bytearray(4)

# DataType Output: memoryview


x = memoryview(bytes(6))

# DataType Output: NoneType


x = None

Numeric Data Type in Python


The numeric data type in Python represents the data that has a numeric value. A
numeric value can be an integer, a floating number, or even a complex number.
These values are defined as Python int, Python float, and Python complex classes
in Python.

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
 Integers – This value is represented by int class. It contains positive or negative
whole numbers (without fractions or decimals). In Python, there is no limit to
how long an integer value can be.
 Float – This value is represented by the float class. It is a real number with a
floating-point representation. It is specified by a decimal point. Optionally, the
character e or E followed by a positive or negative integer may be appended to
specify scientific notation.
 Complex Numbers – Complex number is represented by a complex class. It is
specified as (real part) + (imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of data type.
Python3

# Python program to
# demonstrate numeric value

a=5
print("Type of a: ", type(a))

b = 5.0
print("\nType of b: ", type(b))

c = 2 + 4j
print("\nType of c: ", type(c))

Output:
Type of a: <class 'int'>

Type of b: <class 'float'>

Type of c: <class 'complex'>


Sequence Data Type in Python
The sequence Data Type in Python is the ordered collection of similar or different
data types. Sequences allow storing of multiple values in an organized and efficient
fashion. There are several sequence types in Python –
 Python String
 Python List
 Python Tuple

String Data Type

Strings in Python are arrays of bytes representing Unicode characters. A string is a


collection of one or more characters put in a single quote, double-quote, or triple-
quote. In python there is no character data type, a character is a string of length one.
It is represented by str class.
Creating String

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Strings in Python can be created using single quotes or double quotes or even triple
quotes.
Python3

# Python Program for


# Creation of String

# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))

# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))

# Creating String with triple


# Quotes allows multiple lines
String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)

Output:
String with the use of Single Quotes:
Welcome to the Geeks World

String with the use of Double Quotes:


I'm a Geek
<class 'str'>

String with the use of Triple Quotes:


I'm a Geek and I live in a world of "Geeks"

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
<class 'str'>

Creating a multiline String:


Geeks
For
Life

Accessing elements of String

In Python, individual characters of a String can be accessed by using the method of


Indexing. Negative Indexing allows negative address references to access characters
from the back of the String, e.g. -1 refers to the last character, -2 refers to the second
last character, and so on.
Python3

# Python Program to Access


# characters of String

String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)

# Printing First character


print("\nFirst character of String is: ")
print(String1[0])

# Printing Last character


print("\nLast character of String is: ")
print(String1[-1])

Output:
Initial String:
GeeksForGeeks

First character of String is:


G

Last character of String is:


s
Note – To know more about strings, refer to Python String.

List Data Type

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Lists are just like arrays, declared in other languages which is an ordered collection
of data. It is very flexible as the items in a list do not need to be of the same type.
Creating List
Lists in Python can be created by just placing the sequence inside the square
brackets[].
Python3

# Creating a List
List = []
print("Initial blank List: ")
print(List)

# Creating a List with


# the use of a String
List = ['GeeksForGeeks']
print("\nList with the use of String: ")
print(List)

# Creating a List with


# the use of multiple values
List = ["Geeks", "For", "Geeks"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])

# Creating a Multi-Dimensional List


# (By Nesting a list inside a List)
List = [['Geeks', 'For'], ['Geeks']]
print("\nMulti-Dimensional List: ")
print(List)

Output:
Initial blank List:
[]

List with the use of String:


['GeeksForGeeks']

List containing multiple values:


Geeks
Geeks

Multi-Dimensional List:

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
[['Geeks', 'For'], ['Geeks']]
Python Access List Items
In order to access the list items refer to the index number. Use the index operator [ ]
to access an item in a list. In Python, negative sequence indexes represent positions
from the end of the array. Instead of having to compute the offset as in
List[len(List)-3], it is enough to just write List[-3]. Negative indexing means
beginning from the end, -1 refers to the last item, -2 refers to the second-last item,
etc.
Python3

# Python program to demonstrate


# accessing of element from list

# Creating a List with


# the use of multiple values
List = ["Geeks", "For", "Geeks"]

# accessing a element from the


# list using index number
print("Accessing element from the list")
print(List[0])
print(List[2])

# accessing a element using


# negative indexing
print("Accessing element using negative indexing")

# print the last element of list


print(List[-1])

# print the third last element of list


print(List[-3])

Output:
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
Note – To know more about Lists, refer to Python List.

Tuple Data Type

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Just like a list, a tuple is also an ordered collection of Python objects. The only
difference between a tuple and a list is that tuples are immutable i.e. tuples cannot
be modified after it is created. It is represented by a tuple class.
Creating a Tuple
In Python, tuples are created by placing a sequence of values separated by a
‘comma’ with or without the use of parentheses for grouping the data sequence.
Tuples can contain any number of elements and of any datatype (like strings,
integers, lists, etc.). Note: Tuples can also be created with a single element, but it is
a bit tricky. Having one element in the parentheses is not sufficient, there must be a
trailing ‘comma’ to make it a tuple.
Python3

# Creating an empty tuple


Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)

# Creating a Tuple with


# the use of Strings
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)

# Creating a Tuple with


# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))

# Creating a Tuple with the


# use of built-in function
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)

# Creating a Tuple
# with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)

Output:
Initial empty Tuple:
()

Tuple with the use of String:

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
('Geeks', 'For')

Tuple using List:


(1, 2, 4, 5, 6)

Tuple with the use of function:


('G', 'e', 'e', 'k', 's')

Tuple with nested tuples:


((0, 1, 2, 3), ('python', 'geek'))
Note – The creation of a Python tuple without the use of parentheses is known as
Tuple Packing.
Access Tuple Items
In order to access the tuple items refer to the index number. Use the index operator [
] to access an item in a tuple. The index must be an integer. Nested tuples are
accessed using nested indexing.
Python3

# Python program to
# demonstrate accessing tuple

tuple1 = tuple([1, 2, 3, 4, 5])

# Accessing element using indexing


print("First element of tuple")
print(tuple1[0])

# Accessing element from last


# negative indexing
print("\nLast element of tuple")
print(tuple1[-1])

print("\nThird last element of tuple")


print(tuple1[-3])

Output:
First element of tuple
1

Last element of tuple


5

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4

Third last element of tuple


3
Note – To know more about tuples, refer to Python Tuples.
Boolean Data Type in Python
Data type with one of the two built-in values, True or False. Boolean objects that are
equal to True are truthy (true), and those equal to False are falsy (false). But non-
Boolean objects can be evaluated in a Boolean context as well and determined to be
true or false. It is denoted by the class bool.
Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python
will throw an error.
Python3

# Python program to
# demonstrate boolean type

print(type(True))
print(type(False))

print(type(true))

Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))
NameError: name 'true' is not defined
Set Data Type in Python
In Python, a Set is an unordered collection of data types that is iterable, mutable and
has no duplicate elements. The order of elements in a set is undefined though it may
consist of various elements.
Create a Set in Python
Sets can be created by using the built-in set() function with an iterable object or a
sequence by placing the sequence inside curly braces, separated by a ‘comma’. The
type of elements in a set need not be the same, various mixed-up data type values
can also be passed to the set.
Python3

# Python program to demonstrate


# Creation of Set in Python

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)

# Creating a Set with


# the use of a String
set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)

# Creating a Set with


# the use of a List
set1 = set(["Geeks", "For", "Geeks"])
print("\nSet with the use of List: ")
print(set1)

# Creating a Set with


# a mixed type of values
# (Having numbers and strings)
set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])
print("\nSet with the use of Mixed Values")
print(set1)

Output:
Initial blank Set:
set()

Set with the use of String:


{'F', 'o', 'G', 's', 'r', 'k', 'e'}

Set with the use of List:


{'Geeks', 'For'}

Set with the use of Mixed Values


{1, 2, 4, 6, 'Geeks', 'For'}
Access Set Items
Set items cannot be accessed by referring to an index, since sets are unordered the
items has no index. But you can loop through the set items using a for loop, or ask if
a specified value is present in a set, by using the in the keyword.
Python3

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
# Python program to demonstrate
# Accessing of elements in a set

# Creating a set
set1 = set(["Geeks", "For", "Geeks"])
print("\nInitial set")
print(set1)

# Accessing element using


# for loop
print("\nElements of set: ")
for i in set1:
print(i, end=" ")

# Checking the element


# using in keyword
print("Geeks" in set1)

Output:
Initial set:
{'Geeks', 'For'}

Elements of set:
Geeks For

True
Note – To know more about sets, refer to Python Sets.
Dictionary Data Type in Python
A dictionary in Python is an unordered collection of data values, used to store data
values like a map, unlike other Data Types that hold only a single value as an
element, a Dictionary holds a key: value pair. Key-value is provided in the
dictionary to make it more optimized. Each key-value pair in a Dictionary is
separated by a colon : , whereas each key is separated by a ‘comma’.
Create a Dictionary
In Python, a Dictionary can be created by placing a sequence of elements within
curly {} braces, separated by ‘comma’. Values in a dictionary can be of any
datatype and can be duplicated, whereas keys can’t be repeated and must be
immutable. The dictionary can also be created by the built-in function dict(). An
empty dictionary can be created by just placing it in curly braces{}. Note –
Dictionary keys are case sensitive, the same name but different cases of Key will be
treated distinctly.
Python3

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)

# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)

# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)

# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)

Output:
Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], 'Name': 'Geeks'}
Dictionary with the use of dict():
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with each item as a pair:
{1: 'Geeks', 2: 'For'}
Accessing Key-value in Dictionary
In order to access the items of a dictionary refer to its key name. Key can be used
inside square brackets. There is also a method called get() that will also help in
accessing the element from a dictionary.

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Python3

# Python program to demonstrate


# accessing a element from a Dictionary

# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# accessing a element using key


print("Accessing a element using key:")
print(Dict['name'])

# accessing a element using get()


# method
print("Accessing a element using get:")
print(Dict.get(3))

Output:
Accessing a element using key:
For
Accessing a element using get:
Geeks

Python String
A String is a data structure in Python that represents a sequence
of characters. It is an immutable data type, meaning that once
you have created a string, you cannot change it. Strings are
used widely in many different applications, such as storing and
manipulating text data, representing names, addresses, and
other types of data that can be represented as text.

What is a String in Python?


Python does not have a character data type, a single character
is simply a string with a length of 1.
Example:
"Geeksforgeeks" or 'Geeksforgeeks' or "a"

Python3
print("A Computer Science portal for
geeks")
print('A')

Output:
A Computer Science portal for geeks
A

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Creating a String in Python
Strings in Python can be created using single quotes or double quotes or even triple
quotes. Let us see how we can define a string in Python.

Example:

In this example, we will demonstrate different ways to create a Python String.


We will create a string using single quotes (‘ ‘), double quotes (” “), and triple
double quotes (“”” “””). The triple quotes can be used to declare multiline strings
in Python.

Python3
# Python Program for
# Creation of String

# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)

# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)

# Creating String with triple


# Quotes allows multiple lines
String1 = '''Geeks

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
For
Life'''
print("\nCreating a multiline String: ")
print(String1)

Output:

String with the use of Single Quotes:


Welcome to the Geeks World
String with the use of Double Quotes:
I'm a Geek
String with the use of Triple Quotes:
I'm a Geek and I live in a world of "Geeks"
Creating a multiline String:
Geeks
For
Life

Accessing characters in Python String


In Python, individual characters of a String can be accessed by using the method
of Indexing. Indexing allows negative address references to access characters
from the back of the String, e.g. -1 refers to the last character, -2 refers to the
second last character, and so on.

While accessing an index out of the range will cause an IndexError. Only
Integers are allowed to be passed as an index, float or other types that will cause
a TypeError.

Python String indexing

Example:

In this example, we will define a string in Python and access its characters using
positive and negative indexing. The 0th element will be the first character of the
string whereas the -1th element is the last character of the string.

Python3

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
# Python Program to Access
# characters of String

String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)

# Printing First character


print("\nFirst character of String is:
")
print(String1[0])

# Printing Last character


print("\nLast character of String is:
")
print(String1[-1])

Output:
Initial String:
GeeksForGeeks
First character of String is:
G
Last cha racter of String is:
s
String Slicing
In Python, the String Slicing method is used to access a range of characters in the
String. Slicing in a String is done by using a Slicing operator, i.e., a colon (:). One
thing to keep in mind while using this method is that the string returned after slicing
includes the character at the start index but not the character at the last index.

Example:

In this example, we will use the string-slicing method to extract a substring of the
original string. The [3:12] indicates that the string slicing will start from the 3rd
index of the string to the 12th index, (12th character not including). We can also use
negative indexing in string slicing.

Python3
# Python Program to
# demonstrate String slicing

# Creating a String
String1 = "GeeksForGeeks"
print("Initial String: ")

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
print(String1)

# Printing 3rd to 12th character


print("\nSlicing characters from 3-12:
")
print(String1[3:12])

# Printing characters between


# 3rd and 2nd last character
print("\nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])

Output:
Initial String:
GeeksForGeeks
Slicing characters from 3-12:
ksForGeek
Slicing characters between 3rd and 2nd last character:
ksForGee

Reversing a Python String


By accessing characters from a string, we can also reverse strings in Python . We can
Reverse a string by using String slicing method.

Example:

In this example, we will reverse a string by accessing the index. We did not specify
the first two parts of the slice indicating that we are considering the whole string,
from the start index to the last index.

Python3

#Program to reverse a string


gfg = "geeksforgeeks"
print(gfg[::-1])

Output:

skeegrofskeeg

Example:

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
We can also reverse a string by using built-in join and reversed functions, and
passing the string as the parameter to the reversed() function.

Python3
# Program to reverse a string

gfg = "geeksforgeeks"

# Reverse the string using reversed and join


function
gfg = "".join(reversed(gfg))

print(gfg)

Output:
skeegrofskeeg
Deleting/Updating from a String
In Python, the Updation or deletion of characters from a String is not allowed. This
will cause an error because item assignment or item deletion from a String is not
supported. Although deletion of the entire String is possible with the use of a built-
in del keyword. This is because Strings are immutable, hence elements of a String
cannot be changed once assigned. Only new strings can be reassigned to the same
name.

Updating a character

A character of a string can be updated in Python by first converting the string into
a Python List and then updating the element in the list. As lists are mutable in
nature, we can update the character and then convert the list back into the String.

Another method is using the string slicing method. Slice the string before the
character you want to update, then add the new character and finally add the other
part of the string again by string slicing.

Example:

In this example, we are using both the list and the string slicing method to update a
character. We converted the String1 to a list, changes its value at a particular
element, and then converted it back to a string using the Python string
join() method.

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
In the string-slicing method, we sliced the string up to the character we want to
update, concatenated the new character, and finally concatenate the remaining part
of the string.

Python3

# Python Program to Update


# character of a String

String1 = "Hello, I'm a Geek"


print("Initial String: ")
print(String1)

# Updating a character of the String


## As python strings are immutable, they don't support item updation directly
### there are following two ways
#1
list1 = list(String1)
list1[2] = 'p'
String2 = ''.join(list1)
print("\nUpdating character at 2nd Index: ")
print(String2)

#2
String3 = String1[0:2] + 'p' + String1[3:]
print(String3)

Output:

Initial String:
Hello, I'm a Geek
Updating character at 2nd Index:
Heplo, I'm a Geek
Heplo, I'm a Geek

Updating Entire String

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
As Python strings are immutable in nature, we cannot update the existing string. We
can only assign a completely new value to the variable with the same name.

Example:

In this example, we first assign a value to ‘String1’ and then updated it by assigning
a completely different value to it. We simply changed its reference.

Python3

# Python Program to Update


# entire String

String1 = "Hello, I'm a Geek"


print("Initial String: ")
print(String1)

# Updating a String
String1 = "Welcome to the Geek World"
print("\nUpdated String: ")
print(String1)

Output:

Initial String:
Hello, I'm a Geek
Updated String:
Welcome to the Geek World

Deleting a character

Python strings are immutable, that means we cannot delete a character from it.
When we try to delete thecharacter using the del keyword, it will generate an error.

Python3

# Python Program to delete


# character of a String

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4

String1 = "Hello, I'm a Geek"


print("Initial String: ")
print(String1)

print("Deleting character at 2nd Index: ")


del String1[2]
print(String1)

Output:

Initial String:
Hello, I'm a Geek
Deleting character at 2nd Index:
Traceback (most recent call last):
File "e:\GFG\Python codes\Codes\demo.py", line 9, in <module>
del String1[2]
TypeError: 'str' object doesn't support item deletion

But using slicing we can remove the character from the original string and store the
result in a new string.

Example:

In this example, we will first slice the string up to the character that we want to
delete and then concatenate the remaining string next from the deleted character.

Python3

# Python Program to Delete


# characters from a String

String1 = "Hello, I'm a Geek"


print("Initial String: ")
print(String1)

# Deleting a character

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
# of the String
String2 = String1[0:2] + String1[3:]
print("\nDeleting character at 2nd Index: ")
print(String2)

Output:

Initial String:
Hello, I'm a Geek
Deleting character at 2nd Index:
Helo, I'm a Geek

Deleting Entire String

Deletion of the entire string is possible with the use of del keyword. Further, if we
try to print the string, this will produce an error because the String is deleted and is
unavailable to be printed.

Python3

# Python Program to Delete


# entire String

String1 = "Hello, I'm a Geek"


print("Initial String: ")
print(String1)

# Deleting a String
# with the use of del
del String1
print("\nDeleting entire String: ")
print(String1)

Error:

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Traceback (most recent call last):
File "/home/e4b8f2170f140da99d2fe57d9d8c6a94.py", line 12, in
print(String1)
NameError: name 'String1' is not defined

Escape Sequencing in Python


While printing Strings with single and double quotes in it
causes SyntaxError because String already contains Single and Double Quotes and
hence cannot be printed with the use of either of these. Hence, to print such a String
either Triple Quotes are used or Escape sequences are used to print Strings.

Escape sequences start with a backslash and can be interpreted differently. If single
quotes are used to represent a string, then all the single quotes present in the string
must be escaped and the same is done for Double Quotes.

Example:

Python3

# Python Program for


# Escape Sequencing
# of String

# Initial String
String1 = '''I'm a "Geek"'''
print("Initial String with use of Triple Quotes: ")
print(String1)

# Escaping Single Quote


String1 = 'I\'m a "Geek"'
print("\nEscaping Single Quote: ")
print(String1)

# Escaping Double Quotes


String1 = "I'm a \"Geek\""
print("\nEscaping Double Quotes: ")

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
print(String1)

# Printing Paths with the


# use of Escape Sequences
String1 = "C:\\Python\\Geeks\\"
print("\nEscaping Backslashes: ")
print(String1)

# Printing Paths with the


# use of Tab
String1 = "Hi\tGeeks"
print("\nTab: ")
print(String1)

# Printing Paths with the


# use of New Line
String1 = "Python\nGeeks"
print("\nNew Line: ")
print(String1)

Output:

Initial String with use of Triple Quotes:


I'm a "Geek"
Escaping Single Quote:
I'm a "Geek"
Escaping Double Quotes:
I'm a "Geek"
Escaping Backslashes:
C:\Python\Geeks\
Tab:
Hi Geeks
New Line:
Python
Geeks

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Example:

To ignore the escape sequences in a String, r or R is used, this implies that the
string is a raw string and escape sequences inside it are to be ignored.

Python3

# Printing hello in octal


String1 = "\110\145\154\154\157"
print("\nPrinting in Octal with the use of Escape Sequences: ")
print(String1)

# Using raw String to


# ignore Escape Sequences
String1 = r"This is \110\145\154\154\157"
print("\nPrinting Raw String in Octal Format: ")
print(String1)

# Printing Geeks in HEX


String1 = "This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"
print("\nPrinting in HEX with the use of Escape Sequences: ")
print(String1)

# Using raw String to


# ignore Escape Sequences
String1 = r"This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"
print("\nPrinting Raw String in HEX Format: ")
print(String1)

Output:

Printing in Octal with the use of Escape Sequences:


Hello
Printing Raw String in Octal Format:
This is \110\145\154\154\157
Printing in HEX with the use of Escape Sequences:
This is Geeks in HEX

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Printing Raw String in HEX Format:
This is \x47\x65\x65\x6b\x73 in \x48\x45\x58

Formatting of Strings
Strings in Python can be formatted with the use of format() method which is a very
versatile and powerful tool for formatting Strings. Format method in String contains
curly braces {} as placeholders which can hold arguments according to position or
keyword to specify the order.

Example 1:

In this example, we will declare a string which contains the curly braces {} that acts
as a placeholders and provide them values to see how string declaration position
matters.

Python3

# Python Program for


# Formatting of Strings

# Default order
String1 = "{} {} {}".format('Geeks', 'For', 'Life')
print("Print String in default order: ")
print(String1)

# Positional Formatting
String1 = "{1} {0} {2}".format('Geeks', 'For', 'Life')
print("\nPrint String in Positional order: ")
print(String1)

# Keyword Formatting
String1 = "{l} {f} {g}".format(g='Geeks', f='For', l='Life')
print("\nPrint String in order of Keywords: ")
print(String1)

Output:

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Print String in default order:
Geeks For Life
Print String in Positional order:
For Geeks Life
Print String in order of Keywords:
Life For Geeks

Example 2:

Integers such as Binary, hexadecimal, etc., and floats can be rounded or displayed in
the exponent form with the use of format specifiers.

Python3

# Formatting of Integers
String1 = "{0:b}".format(16)
print("\nBinary representation of 16 is ")
print(String1)

# Formatting of Floats
String1 = "{0:e}".format(165.6458)
print("\nExponent representation of 165.6458 is ")
print(String1)

# Rounding off Integers


String1 = "{0:.2f}".format(1/6)
print("\none-sixth is : ")
print(String1)

Output:

Binary representation of 16 is
10000
Exponent representation of 165.6458 is
1.656458e+02
one-sixth is :
0.17

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Example 3:

A string can be left, right, or center aligned with the use of format specifiers,
separated by a colon(:). The (<) indicates that the string should be aligned to the left,
(>) indicates that the string should be aligned to the right and (^) indicates that the
string should be aligned to the center. We can also specify the length in which it
should be aligned. For example, (<10) means that the string should be aligned to the
left within a field of width of 10 characters.

Python3

# String alignment
String1 = "|{:<10}|{:^10}|{:>10}|".format('Geeks',
'for',
'Geeks')
print("\nLeft, center and right alignment with Formatting: ")
print(String1)

# To demonstrate aligning of spaces


String1 = "\n{0:^16} was founded in {1:<4}!".format("GeeksforGeeks",
2009)
print(String1)

Output:

Left, center and right alignment with Formatting:


|Geeks | for | Geeks|
GeeksforGeeks was founded in 2009 !

Example 4:

Old-style formatting was done without the use of the format method by
using the % operator

Python3

# Python Program for


# Old Style Formatting

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
# of Integers

Integer1 = 12.3456789
print("Formatting in 3.2f format: ")
print('The value of Integer1 is %3.2f' % Integer1)
print("\nFormatting in 3.4f format: ")
print('The value of Integer1 is %3.4f' % Integer1)

Output:

Formatting in 3.2f format:


The value of Integer1 is 12.35
Formatting in 3.4f format:
The value of Integer1 is 12.3457

Useful Python String Operations


 Logical Operators on String
 String Formatting using %
 String Template Class
 Split a string
 Python Docstrings
 String slicing
 Find all duplicate characters in string
 Reverse string in Python (5 different ways)
 Python program to check if a string is palindrome or not
Python String constants

Built-In Function Description

Concatenation of the ascii_lowercase and ascii_uppercase


string.ascii_letters
constants.

string.ascii_lowercase Concatenation of lowercase letters

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Built-In Function Description

string.ascii_uppercase Concatenation of uppercase letters

string.digits Digit in strings

string.hexdigits Hexadigit in strings

string.letters concatenation of the strings lowercase and uppercase

string.lowercase A string must contain lowercase letters.

string.octdigits Octadigit in a string

string.punctuation ASCII characters having punctuation characters.

string.printable String of characters which are printable

Returns True if a string ends with the given suffix


String.endswith()
otherwise returns False

Returns True if a string starts with the given prefix


String.startswith()
otherwise returns False

Returns “True” if all characters in the string are digits,


String.isdigit()
Otherwise, It returns “False”.

String.isalpha() Returns “True” if all characters in the string are alphabets,

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Built-In Function Description

Otherwise, It returns “False”.

string.isdecimal() Returns true if all characters in a string are decimal.

one of the string formatting methods in Python3, which


str.format()
allows multiple substitutions and value formatting.

Returns the position of the first occurrence of substring in


String.index
a string

string.uppercase A string must contain uppercase letters.

A string containing all characters that are considered


string.whitespace
whitespace.

Method converts all uppercase characters to lowercase


string.swapcase()
and vice versa of the given string, and returns it

returns a copy of the string where all occurrences of a


replace()
substring is replaced with another substring.

Deprecated string functions

Built-In Function Description

string.Isdecimal Returns true if all characters in a string are decimal

String.Isalnum Returns true if all the characters in a given string are

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Built-In Function Description

alphanumeric.

string.Istitle Returns True if the string is a title cased string

splits the string at the first occurrence of the separator and


String.partition
returns a tuple.

String.Isidentifier Check whether a string is a valid identifier or not.

String.len Returns the length of the string.

Returns the highest index of the substring inside the string if


String.rindex
substring is found.

String.Max Returns the highest alphabetical character in a string.

String.min Returns the minimum alphabetical character in a string.

String.splitlines Returns a list of lines in the string.

string.capitalize Return a word with its first character capitalized.

string.expandtabs Expand tabs in a string replacing them by one or more spaces

string.find Return the lowest indexing a sub string.

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Built-In Function Description

string.rfind find the highest index.

Return the number of (non-overlapping) occurrences of


string.count
substring sub in string

Return a copy of s, but with upper case, letters converted to


string.lower
lower case.

Return a list of the words of the string, If the optional second


string.split
argument sep is absent or None

Return a list of the words of the string s, scanning s from the


string.rsplit()
end.

rpartition() Method splits the given string into three parts

Return a list of the words of the string when only used with
string.splitfields
two arguments.

Concatenate a list or tuple of words with intervening


string.join
occurrences of sep.

It returns a copy of the string with both leading and trailing


string.strip()
white spaces removed

string.lstrip Return a copy of the string with leading white spaces

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Built-In Function Description

removed.

string.rstrip Return a copy of the string with trailing white spaces removed.

string.swapcase Converts lower case letters to upper case and vice versa.

string.translate Translate the characters using table

string.upper lower case letters converted to upper case.

string.ljust left-justify in a field of given width.

string.rjust Right-justify in a field of given width.

string.center() Center-justify in a field of given width.

Pad a numeric string on the left with zero digits until the given
string-zfill
width is reached.

Return a copy of string s with all occurrences of substring old


string.replace
replaced by new.

Returns the string in lowercase which can be used for caseless


string.casefold()
comparisons.

string.encode Encodes the string into any encoding supported by Python.

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Built-In Function Description

The default encoding is utf-8.

string.maketrans Returns a translation table usable for str.translate()

Advantages of String in Python:

 Strings are used at a larger scale i.e. for a wide areas of operations such as
storing and manipulating text data, representing names, addresses, and other
types of data that can be represented as text.
 Python has a rich set of string methods that allow you to manipulate and work
with strings in a variety of ways. These methods make it easy to perform
common tasks such as converting strings to uppercase or lowercase, replacing
substrings, and splitting strings into lists.
 Strings are immutable, meaning that once you have created a string, you cannot
change it. This can be beneficial in certain situations because it means that you
can be confident that the value of a string will not change unexpectedly.
 Python has built-in support for strings, which means that you do not need to
import any additional libraries or modules to work with strings. This makes it
easy to get started with strings and reduces the complexity of your code.
 Python has a concise syntax for creating and manipulating strings, which makes
it easy to write and read code that works with strings.

Drawbacks of String in Python:

 When we are dealing with large text data, strings can be inefficient. For
instance, if you need to perform a large number of operations on a string, such as
replacing substrings or splitting the string into multiple substrings, it can be slow
and consume a lot resources.

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
 Strings can be difficult to work with when you need to represent complex data
structures, such as lists or dictionaries. In these cases, it may be more efficient to
use a different data type, such as a list or a dictionary, to represent the data.

Retrieving And Updating Data Contained in Shelve in Python


In Python shelve you access the keys randomly. In order to access the keys
randomly in python shelve we use open() function. This function works a lot like the
file open() function in File handling. Syntax for open the file using Python shelve

shelve.open(filename, flag='c' , writeback=True)

In Order to access the keys randomly in shelve in Python, we have to take three
steps:

 Storing Python shelve data


 Retrieving Python shelve data
 Updating Python shelve data
Storing Python shelve data :
In order to store python shelve data, we have to create a file with full of datasets and
open them with a open() function this function open a file which we have created.

# At first, we have to import the 'Shelve' module.


import shelve

# In this step, we create a shelf file.


shfile = shelve.open("shelf_file")

# we create a data object which in this case is a book_list.


my_book_list =['bared_to_you', 'The_fault_in_our_stars',
'The_boy_who_never_let_her_go']

# we are assigning a dictionary key to the list


# which we will want to retrieve
shfile['book_list']= my_book_list

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
# now, we simply close the shelf file.
shfile.close()

Retrieving Python shelve data :


After storing a shelve data, we have to retrieve some data from a file in order to do
that we use index operator [] as we do in lists and in many other data types.

# At first, we import the 'Shelve' module.


import shelve

# In this step, we create a shelf file.


var = shelve.open("shelf_file")

# Now, this 'var' variable points to all the


# data objects in the file 'shelf_file'.
print(var['book_list'])

# now, we simply close the file 'shelf_file'.


var.close()

Output :

['bared_to_you', 'The_fault_in_our_stars', 'The_boy_who_never_let_her_go']

Updating Python shelve data :


In order to update a python shelve data, we use append() function or we can easily
update as we do in lists and in other data types. In order to make our changes
permanent we use sync() function.

# At first, we have to import the 'Shelve' module.


import shelve

# In this step, we create a shelf file.

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
var = shelve.open("shelf_file", writeback = True)

# inputting total values we want to add


# to the already existing list in shelf_file.
val1 = int(input("Enter the number of values "))

for x in range(val1):

val = input("\n Enter the value\t")

var['book_list'].append(val)

# Now, this 'var' variable will help in printing


# the data objects in the file 'shelf_file'.
print(var['book_list'])

# to make our changes permanent, we use


# synchronize function.
var.sync()

# now, we simply close the file 'shelf_file'.


var.close()

Input :

Enter the number of values 5

Enter the value Who moved my cheese?

Enter the value Our impossible love

Enter the value Bourne Identity

Enter the value Hush

Enter the value Knock-Knock

Output :

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
['bared_to_you', 'The_fault_in_our_stars', 'The_boy_who_never_let_her_go',

'Who moved my cheese?', 'Our impossible love', 'Bourne Identity',

'Hush', 'Knock-Knock']

Note : Input and Output depend upon user, user can update anything in a file which
user want according to user input, output will be changed.

File Handling in Python


File handling in Python is a powerful and versatile tool that can be used to
perform a wide range of operations. However, it is important to carefully consider
the advantages and disadvantages of file handling when writing Python programs, to
ensure that the code is secure, reliable, and performs well.

Python File Handling


Python too supports file handling and allows users to handle files i.e., to read
and write files, along with many other file handling options, to operate on files. The
concept of file handling has stretched over various other languages, but the
implementation is either complicated or lengthy, but like other concepts of Python,
this concept here is also easy and short. Python treats files differently as text or
binary and this is important. Each line of code includes a sequence of characters and
they form a text file. Each line of a file is terminated with a special character, called
the EOL or End of Line characters like comma {,} or newline character. It ends the
current line and tells the interpreter a new one has begun. Let’s start with the
reading and writing files.

Advantages of File Handling

 Versatility: File handling in Python allows you to perform a wide range of


operations, such as creating, reading, writing, appending, renaming, and deleting
files.
 Flexibility: File handling in Python is highly flexible, as it allows you to work
with different file types (e.g. text files, binary files, CSV files, etc.), and to
perform different operations on files (e.g. read, write, append, etc.).
 User–friendly: Python provides a user-friendly interface for file handling,
making it easy to create, read, and manipulate files.

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
 Cross-platform: Python file-handling functions work across different platforms
(e.g. Windows, Mac, Linux), allowing for seamless integration and
compatibility.

Disadvantages of File Handling

 Error-prone: File handling operations in Python can be prone to errors,


especially if the code is not carefully written or if there are issues with the file
system (e.g. file permissions, file locks, etc.).
 Security risks: File handling in Python can also pose security risks, especially if
the program accepts user input that can be used to access or modify sensitive
files on the system.
 Complexity: File handling in Python can be complex, especially when working
with more advanced file formats or operations. Careful attention must be paid to
the code to ensure that files are handled properly and securely.
 Performance: File handling operations in Python can be slower than other
programming languages, especially when dealing with large files or performing
complex operations.
For this article, we will consider the following “geeks.txt” file as an example.

Hello world

GeeksforGeeks

123 456

Working of open() Function in Python


Before performing any operation on the file like reading or writing, first, we have to
open that file. For this, we should use Python’s inbuilt function open() but at the
time of opening, we have to specify the mode, which represents the purpose of the
opening file.

f = open(filename, mode)
Where the following mode is supported:

1. r: open an existing file for a read operation.

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
2. w: open an existing file for a write operation. If the file already contains some
data then it will be overridden but if the file is not present then it creates the file
as well.
3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. The previous data in the file will be
overridden.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing data.

Working in Read mode

There is more than one way to read a file in Python . Let us see how we can read the
content of a file in read mode.

Example 1: The open command will open the file in the read mode and the for loop
will print each line present in the file.

Python3

# a file named "geek", will be opened with the reading mode.


file = open('geek.txt', 'r')

# This will print every line one by one in the file


for each in file:
print (each)

Output:

Hello world

GeeksforGeeks

123 456

Example 2: In this example, we will extract a string that contains all characters in
the file then we can use file.read().

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Python3

# Python code to illustrate read() mode


file = open("geeks.txt", "r")
print (file.read())

Output:

Hello world

GeeksforGeeks

123 456

Example 3: In this example, we will see how we can read a file using the with
statement.

Python3

# Python code to illustrate with()


with open("geeks.txt") as file:
data = file.read()

print(data)

Output:

Hello world

GeeksforGeeks

123 456

Example 4: Another way to read a file is to call a certain number of characters like
in the following code the interpreter will read the first five characters of stored data
and return it as a string:

Python3

# Python code to illustrate read() mode character wise


file = open("geeks.txt", "r")
print (file.read(5))

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Output:

Hello

Example 5:

We can also split lines while reading files in Python. The split() function splits the
variable when space is encountered. You can also split using any characters as you
wish.

Python3

# Python code to illustrate split() function


with open("geeks.txt", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word)

Output:

['Hello', 'world']

['GeeksforGeeks']

['123', '456']

Creating a File using the write() Function


Just like reading a file in Python, there are a number of ways to write in a file in
Python. Let us see how we can write the content of a file using the write() function
in Python.

Working in Write Mode

Let’s see how to create a file and how the write mode works.

Example 1: In this example, we will see how the write mode and the write()
function is used to write in a file. The close() command terminates all the resources
in use and frees the system of this particular program.

Python3

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
# Python code to create a file
file = open('geek.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()

Output:

This is the write commandIt allows us to write in a particular file

Example 2: We can also use the written statement along with the with() function.

Python3

# Python code to illustrate with() alongwith write()


with open("file.txt", "w") as f:
f.write("Hello World!!!")

Output:

Hello World!!!

Working of Append Mode

Let us see how the append mode works.

Example: For this example, we will use the file created in the previous example.

Python3

# Python code to illustrate append() mode


file = open('geek.txt', 'a')
file.write("This will add this line")
file.close()

Output:

This is the write commandIt allows us to write in a particular fileThis will add this
line

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
There are also various other commands in file handling that are used to handle
various tasks:

rstrip(): This function strips each line of a file off spaces from the right-hand side.

lstrip(): This function strips each line of a file off spaces from the left-hand side.

It is designed to provide much cleaner syntax and exception handling when you are
working with code. That explains why it’s good practice to use them with a
statement where applicable. This is helpful because using this method any files
opened will be closed automatically after one is done, so auto-cleanup.

Implementing all the functions in File Handling

In this example, we will cover all the concepts that we have seen above. Other than
those, we will also see how we can delete a file using the remove() function from
Python os module.

Python3

import os

def create_file(filename):
try:
with open(filename, 'w') as f:
f.write('Hello, world!\n')
print("File " + filename + " created successfully.")
except IOError:
print("Error: could not create file " + filename)

def read_file(filename):
try:
with open(filename, 'r') as f:
contents = f.read()

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
print(contents)
except IOError:
print("Error: could not read file " + filename)

def append_file(filename, text):


try:
with open(filename, 'a') as f:
f.write(text)
print("Text appended to file " + filename + " successfully.")
except IOError:
print("Error: could not append to file " + filename)

def rename_file(filename, new_filename):


try:
os.rename(filename, new_filename)
print("File " + filename + " renamed to " + new_filename + " successfully.")
except IOError:
print("Error: could not rename file " + filename)

def delete_file(filename):
try:
os.remove(filename)
print("File " + filename + " deleted successfully.")
except IOError:
print("Error: could not delete file " + filename)

if __name__ == '__main__':
filename = "example.txt"
new_filename = "new_example.txt"

create_file(filename)
read_file(filename)

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
append_file(filename, "This is some additional text.\n")
read_file(filename)
rename_file(filename, new_filename)
read_file(new_filename)
delete_file(new_filename)

Output:

File example.txt created successfully.


Hello, world!
Text appended to file example.txt successfully.
Hello, world!
This is some additional text.
File example.txt renamed to new_example.txt
successfully.
Hello, world!
This is some additional text.
File new_example.txt deleted successfully.

Reading and Writing to text files in Python


Python provides inbuilt functions for creating, writing, and
reading files. There are two types of files that can be handled in
python, normal text files and binary files (written in binary
language, 0s, and 1s).
 Text files: In this type of file, Each line of text is terminated
with a special character called EOL (End of Line), which is the
new line character (‘\n’) in python by default.
 Binary files: In this type of file, there is no terminator for a
line, and the data is stored after converting it into machine-
understandable binary language.
In this article, we will be focusing on opening, closing, reading,
and writing data in a text file.

File Access Modes


Access modes govern the type of operations possible in the
opened file. It refers to how the file will be used once its opened.
These modes also define the location of the File Handle in the
file. File handle is like a cursor, which defines from where the

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
data has to be read or written in the file. There are 6 access
modes in python.
1. Read Only (‘r’) : Open text file for reading. The handle is
positioned at the beginning of the file. If the file does not
exists, raises the I/O error. This is also the default mode in
which a file is opened.
2. Read and Write (‘r+’): Open the file for reading and
writing. The handle is positioned at the beginning of the file.
Raises I/O error if the file does not exist.
3. Write Only (‘w’) : Open the file for writing. For the existing
files, the data is truncated and over-written. The handle is
positioned at the beginning of the file. Creates the file if the
file does not exist.
4. Write and Read (‘w+’) : Open the file for reading and
writing. For an existing file, data is truncated and over-
written. The handle is positioned at the beginning of the file.
5. Append Only (‘a’): Open the file for writing. The file is
created if it does not exist. The handle is positioned at the
end of the file. The data being written will be inserted at the
end, after the existing data.
6. Append and Read (‘a+’) : Open the file for reading and
writing. The file is created if it does not exist. The handle is
positioned at the end of the file. The data being written will
be inserted at the end, after the existing data.
How Files are Loaded into Primary
Memory
There are two kinds of memory in a computer i.e. Primary and
Secondary memory every file that you saved or anyone saved is
on secondary memory cause any data in primary memory is
deleted when the computer is powered off. So when you need to
change any text file or just to work with them in python you
need to load that file into primary memory. Python interacts with
files loaded in primary memory or main memory through “file
handlers” ( This is how your operating system gives access to
python to interact with the file you opened by searching the file
in its memory if found it returns a file handler and then you can
work with the file ).

Opening a File

It is done using the open() function. No module is required to be


imported for this function.
File_object = open(r"File_Name","Access_Mode")

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
The file should exist in the same directory as the python
program file else, the full address of the file should be written in
place of the filename. Note: The r is placed before the filename
to prevent the characters in the filename string to be treated as
special characters. For example, if there is \temp in the file
address, then \t is treated as the tab character, and an error is
raised of invalid address. The r makes the string raw, that is, it
tells that the string is without any special characters. The r can
be ignored if the file is in the same directory and the address is
not being placed.

Python
# Open function to open the file
"MyFile1.txt"
# (same directory) in append mode and
file1 = open("MyFile1.txt","a")

# store its reference in the variable file1


# and "MyFile2.txt" in D:\Text in file2
file2 = open(r"D:\Text\MyFile2.txt","w+")

Here, file1 is created as an object for MyFile1 and file2 as object


for MyFile2

Closing a file

close() function closes the file and frees the memory space
acquired by that file. It is used at the time when the file is no
longer needed or if it is to be opened in a different file mode.
File_object.close()

Python
# Opening and Closing a file
"MyFile.txt"
# for object name file1.
file1 = open("MyFile.txt","a")
file1.close()

Writing to a file

There are two ways to write in a file.


1. write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
1. writelines() : For a list of string elements, each string is
inserted in the text file.Used to insert multiple strings at a
single time.
File_object.writelines(L) for L = [str1, str2, str3]

Reading from a file

There are three ways to read data from a text file.


1. read() : Returns the read bytes in form of a string. Reads n
bytes, if no n specified, reads the entire file.
File_object.read([n])
1. readline() : Reads a line of the file and returns in form of a
string.For specified n, reads at most n bytes. However, does
not reads more than one line, even if n exceeds the length of
the line.
File_object.readline([n])
1. readlines() : Reads all the lines and return them as each line
a string element in a list.
File_object.readlines()
Note: ‘\n’ is treated as a special character of two bytes

Python3
# Program to show various ways to read and
# write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is
London \n"]

# \n is placed to indicate EOL (End of Line)


file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes

file1 = open("myfile.txt","r+")

print("Output of Read function is ")


print(file1.read())
print()

# seek(n) takes the file handle to the nth


# byte from the beginning.
file1.seek(0)

print( "Output of Readline function is ")


print(file1.readline())
print()

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
file1.seek(0)

# To show difference between read and readline


print("Output of Read(9) function is ")
print(file1.read(9))
print()

file1.seek(0)

print("Output of Readline(9) function is ")


print(file1.readline(9))

file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()

Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Output of Readline function is
Hello
Output of Read(9) function is
Hello
Th
Output of Readline(9) function is
Hello
Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Paris \n',
'This is London \n']

Appending to a file

Python3
# Python program to illustrate
# Append vs write mode
file1 = open("myfile.txt","w")

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
L = ["This is Delhi \n","This is Paris \n","This is
London \n"]
file1.writelines(L)
file1.close()

# Append-adds at last
file1 = open("myfile.txt","a")#append mode
file1.write("Today \n")
file1.close()

file1 = open("myfile.txt","r")
print("Output of Readlines after appending")
print(file1.readlines())
print()
file1.close()

# Write-Overwrites
file1 = open("myfile.txt","w")#write mode
file1.write("Tomorrow \n")
file1.close()

file1 = open("myfile.txt","r")
print("Output of Readlines after writing")
print(file1.readlines())
print()
file1.close()

Output:
Output of Readlines after appending
['This is Delhi \n', 'This is Paris \n', 'This is London
\n', 'Today \n']

Output of Readlines after writing


['Tomorrow \n']

Reading binary files in Python


Reading binary files is an important skill for working with data
(non-textual) such as images, audio, and videos. Using file mode
and the “read” method you can easily read binary
files. Python has the ability to handle the data and consent
provides various help with certain criteria. Whether you are
dealing with multimedia files, compressed data, or custom
binary formats, Python’s ability to handle binary data
empowers you to create powerful and versatile applications for a
wide range of use cases. In this article, you will learn What
binary files are and how to read data into a byte array,
and Read binary data into chunks? and so on.

What are Binary files?

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Generally, binary means two. In computer science, binary files
are stored in a binary format having digits 0’s and 1’s. For
example, the number 9 in binary format is represented as
‘1001’. In this way, our computer stores each and every file in a
machine-readable format in a sequence of binary digits. The
structure and format of binary files depend on the type of file.
Image files have different structures when compared to audio
files. However, decoding binary files depends on the complexity
of the file format. In this article, let’s understand the reading of
binary files.

Python Read A Binary File

To read a binary file,


Step 1: Open the binary file in binary mode
To read a binary file in Python, first, we need to open it in binary
mode (‘”rb”‘). We can use the ‘open()’ function to achieve this.
Step 2: Create a binary file
To create a binary file in Python, You need to open the file in
binary write mode ( wb ). For more refer to this article.
Step 3: Read the binary data
After opening the binary file in binary mode, we can use the
read() method to read its content into a variable. The” read()”
method will return a sequence of bytes, which represents the
binary data.
Step 4: Process the binary data
Once we have read the binary data into a variable, we can
process it according to our specific requirements. Processing the
binary data could involve various tasks such as decoding binary
data, analyzing the content, or writing the data to another
binary file.
Step 5: Close the file
After reading and processing the binary data, it is essential to
close the file using the “close()” method to release system
resources and avoid potential issues with file access.

 Python3
# Opening the binary file in binary mode as r

f = open("files.zip", mode="rb")

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4

# Reading file data with read() method


data = f.read()

# Knowing the Type of our data


print(type(data))

# Printing our byte sequenced data


print(data)

# Closing the opened file


f.close()

Output:
In the output, we see a sequence of byte data as bytes are the
fundamental unit of binary representation.
b’PK\x03\x04\x14\x00\x00\x00\x08\x00U\xbd\xebV\
xc2=j\x87\x1e\x00\x00\x00!\x00\x00\x00\n\x00\x00\
x00TODO11.txt\xe3\xe5JN,\xceH-/\xe6\xe5\x82\xc0\
xcc\xbc\x92\xd4\x9c\x9c\xcc\x82\xc4\xc4\x12^.w7w\
x00PK\x01\x02\x14\x00\x14\x00\x00\x00\x08\x00U\
xbd\xebV\xc2=j\x87\x1e\x00\x00\x00!\x00\x00\x00\
n\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\x00\
x00\x00\x00\x00\x00TODO11.txtPK\x05\x06\x00\x00\
x00\x00\x01\x00\x01\x008\x00\x00\x00F\x00\x00\
x00\x00\x00′

Reading binary data into a byte array

This given code demonstrates how to read binary data from a


file into a byte array and then To read binary data into a binary
array print the data using a while loop. Let’s explain the code
step-by-step:
Open the Binary File
This line opens the binary file named “string.bin” in binary mode
(‘”rb”‘). The file is opened for reading, and the file object is
stored in the variable ‘file’.

 Python3
# Open the binary file
file = open("string.bin",
"rb")

Reading the first three bytes

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
This line reads the first three bytes from the binary file and
stores them in the variable “data”. The “read(3)” method bytes
from the file and advance the pointer accordingly.

 Python3
data =
file.read(3)

Print data using a “while ” Loop


The loop will keep reading and printing three bytes at a time
until the end of the file is reached. Once the end of the file is
reached, the read() method will return an empty bytes object,
which evaluates to False in the while loop condition, and the
loop will terminate.

 Python3
while data:
print(data)
data =
file.read(3)

Close the Binary File


Finally, after the loop has finished reading and printing the data,
we close the binary file using the ‘close()’ method to release
system resources.

 Python3
file.close(
)

Now by using the above steps in one, we will get this :


The code output will depend on the content of
the “string.bin” binary file. The code reads and prints the data
in chunks of three bytes at a time until the end of the file is
reached. Each iteration of the loop will print the three bytes read
from the file.

 Python
# Open the binary file
file = open("string.bin", "rb")
# Reading the first three bytes from the binary
file
data = file.read(3)
# Printing data by iterating with while loop

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
while data:
print(data)
data = file.read(3)
# Close the binary file
file.close()

For example, if the content of “string.bin” is b’GeeksForGeeks’


(a sequence of six bytes), the output will be:
Output:
b 'Gee'
b ' ksf'
b 'org'
b 'eek'
b 's'

Read Binary files in Chunks

To Read binary file data in chunks we use a while loop to read


the binary data from the file in chunks of the specified size
(chunk_size). The loop continues until the end of the file is
reached, and each chunk of data is processed accordingly.
In this “chunk_size=1024” is used to specify the size of each
chunk to read the binary file. file = open(“binary_file.bin”, “rb”):
This line opens the binary file named “binary_file.bin” in binary
mode (“rb”). while True is used to sets up an infinite loop that
will keep reading the file in chunks until the end of the file is
reached. “chunk = file. read(chunk_size)” is Inside the loop, and
the read(chunk_size) method is used to read a chunk of binary
data from the file.

 Python3
# Specify the size of each chunk to read
chunk_size = 10

file = open("binary_file.bin", "rb")


# Using while loop to iterate the file data
while True:
chunk = file.read(chunk_size)
if not chunk:
break
# Processing the chunk of binary data
print(f"Read {len(chunk)} bytes:
{chunk}")

The output of the code will depend on the content of the


“binary_file.bin” binary file and the specified “chunk_size”, For

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
example, if the file contains the binary data “b” Hello, this is
binary data!’, and the chunk_size is set to 10, the output will be:
Output :
Read 10 bytes: b'Hello, thi'
Read 10 bytes: b's is binar'
Read 7 bytes: b'y data!'

Outputs vary depending on the binary file data we are reading


and also on the chunk size we are specifying.

Read Binary file Data into Array

To read a binary file into an array.bin and used the “wb” mode
to write a given binary file. The “array” is the name of the file.
assigned array as num=[3,6,9,12,18] to get the array in byte
format. use byte array().
To write an array to the file we use:

 Python3
file=open("array","wb"
)
num=[3,6,9,12,18]
array=bytearray(num)
file.write(array)
file.close()

To read the written array from the given file, we have used the
same file i.e., file=open(“array”, “rb”). rb used to read the array
from the file. The list() is used to create a list object.
number=list(file. read(3)). To read the bytes from the file. read()
is used.

 Python3
file=open("array","rb")
number=list(file.read(3
))
print (number)
file.close()

Output:
[3,6,9]

Read Binary files in Python using NumPy

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
To read a binary file into a NumPy array, import module NumPy.
The “dtype” is “np.unit8” which stands for “unsigned 8-bit
integer” This means that each item in the array is an 8-bit (1
byte) integer, with values that can range from 0 to 255.

 Python3
import numpy as np

# Open the file in binary mode


with open('myfile.bin', 'rb') as f:
# Read the data into a NumPy array
array = np.fromfile(f, dtype=np.uint8) # Change dtype
according to your data

Remember to change your file to your binary files


Output:
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
dtype=np.uint8)

Access Relation Databases with


Python
Databases are powerful tools for data scientists. DB-API is
Python’s standard API used for accessing databases. It allows
you to write a single program that works with multiple kinds of
relational databases instead of writing a separate program for
each one. This is how a typical user accesses databases using
Python code written on a Jupyter notebook, a Web-based editor.

There is a mechanism by which the Python program


communicates with the DBMS:
 The application program begins its database access with one
or more API calls that connect the program to the DBMS.
 Then to send the SQL statement to the DBMS, the program
builds the statement as a text string and then makes an API
call to pass the contents to the DBMS.
 The application program makes API calls to check the status
of its DBMS request and to handle errors.
 The application program ends its database access with an API
call that disconnects it from the database.

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4

The two main concepts in the Python DB-API are:


1) Connection objects used for
 Connect to a database
 Manage your transactions.
Following are a few connection methods:
 cursor(): This method returns a new cursor object using the
connection.
 commit(): This method is used to commit any pending
transaction to the database.
 rollback(): This method causes the database to roll back to
the start of any pending transaction.
 close(): This method is used to close a database connection.
2) Query objects are used to run queries.
This is a python application that uses the DB-API to query a
database.

 Python3
from dbmodule import connect

# Create connection object


connection = connect('databasename', 'username',
'pswd')

# Create a cursor object


cursor = connection.cursor()

# Run queries
cursor.execute('select * from mytable')
results = cursor.fetchall()

# Free resources
cursor.close()
connection.close()

1. First, we import the database module by using the connect


API from that module. To open a connection to the database,
you use the connection function and pass in the

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
parameters that are the database name, username, and
password. The connect function returns the connection
object.
2. After this, we create a cursor object on the connection
object. The cursor is used to run queries and get the results.
3. After running the queries using the cursor, we also use the
cursor to fetch the results of the query.
4. Finally, when the system is done running the queries, it frees
all resources by closing the connection. Remember that it
is always important to close connections to avoid unused
connections taking up resources.
Types of NoSQL database: Types of NoSQL databases and the
name of the database system that falls in that category are:
Graph Databases: Examples – Amazon Neptune, Neo4j
1.
Key value store: Examples – Memcached, Redis, Coherence
2.
Column: Examples – Hbase, Big Table, Accumulo
3.
Document-based: Examples – MongoDB, CouchDB,
4.
Cloudant
When should NoSQL be used:
1. When a huge amount of data needs to be stored and
retrieved.
2. The relationship between the data you store is not that
important
3. The data changes over time and is not structured.
4. Support of Constraints and Joins is not required at the
database level
5. The data is growing continuously and you need to scale the
database regularly to handle the data.
In conclusion, NoSQL databases offer several benefits over
traditional relational databases, such as scalability, flexibility,
and cost-effectiveness. However, they also have several
drawbacks, such as a lack of standardization, lack of ACID
compliance, and lack of support for complex queries. When
choosing a database for a specific application, it is important to
weigh the benefits and drawbacks carefully to determine the
best fit.

Network Programming Python –


HTTP Clients
The request from the client in HTTP protocol reaches the server
and fetches some data assuming it to be a valid request. This
response from the server can be analyzed by using various
methods provided by the requests module. Some of the ways
below provide information about the response sent from the
server to the Python program running on the client-side :

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Getting initial Response
The get() method is used to get the basic information of the
resources used at the server-side. This function fetches the data
from the server and returns as a response object which can be
printed in a simple text format.

Python3
# Import libraries
import requests

# Sending Request
req =
requests.get('https://www.geeksforgeeks.org/')

# Show results
print(req.text[:2000])

Output:

Getting session-info
The session() method returns the session object which provides
certain parameters to manipulate the requests. It can also
manipulate cookies for all the requests initiated from the session

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
object. If a large amount of requests are made to a single host
then, the associated TCP connection is recalled.

Python3
# Import Libraries
import requests

# Creating Session
s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/
419735271')

# Getting Response
r = s.get('http://httpbin.org/cookies')

# Show Response
print(r.text)

Output:
{
"cookies": {
"sessioncookie": "419735271"
}
}

Error Handling
If some error is raised in processing the request to the server,
the exception is raised by the program which can be handled
using the timeout attribute, which defines the time value until
the program waits and after that, it raises the timeout error.

Python3
# Import Libraries
import requests

# Error Handling
try:

# Creating Request
req = requests.get('https://www.geeksforgeeks.org/',
timeout=0.000001)

except requests.exceptions.RequestException as e:

# Raising Error
raise SystemExit(e)

Output:

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
HTTPSConnectionPool(host=’www.geeksforgeeks.org’
, port=443): Max retries exceeded with url: / (Caused
by
ConnectTimeoutError(<urllib3.connection.HTTPSConn
ection object at 0x0000018CFDAD83C8>,
‘Connection to www.geeksforgeeks.org timed out.
(connect timeout=1e-06)’))

Python - Web Servers


Python is versatile enough to create many types of
applications ans programs that drive the internet or other
computer networks. One important aspect of internet is the
web servers that are at the root of the client server model.
In this chapter we will see few web servers which are
created uaing pure python language.

Gunicorn
Gunicorn is a stand-alone web server which has a central
master process tasked with managing the initiated worker
processes of differing types. These worker processes then
handle and deal with the requests directly. And all this can
be configured and adapted to suit the diverse needs of
production scenarios.

Important Features

 It supports WSGI and can be used with any WSGI


running Python application and framework
 It can also be used as a drop-in replacement for Paster
(ex: Pyramid), Django's Development Server, web2py,
etc
 Offers the choice of various worker
types/configurations and automatic worker process
management
 HTTP/1.0 and HTTP/1.1 (Keep-Alive) support through
synchronous and asynchronous workers
 Comes with SSL support
 Extensible with hooks

CherryPy WSGI Server

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
CherryPy is a self contained web framework as it can run on
its own without the need of additional software. It has its
own WSGI, HTTP/1.1-compliant web server. As it is a WSGI
server, it can be used to serve any other WSGI Python
application as well, without being bound to CherryPy's
application development framework.

Important Features

 It can run any Python web applications running on


WSGI.
 It can handle static files and it can just be used to serve
files and folders alone.
 It is thread-pooled.
 It comes with support for SSL.
 It is an easy to adapt, easy to use pure-Python
alternative which is robust and reliable.

Twisted Web
It is a web server that comes with the Twisted networking
library. Whereas Twisted itself is "an event-driven
networking engine", the Twisted Web server runs on WSGI
and it is capable of powering other Python web applications.

Important Features

 It runs WSGI Python applications


 It can act like a Python web server framework, allowing
you to program it with the language for custom HTTP
serving purposes
 It offers simple and fast prototyping ability through
Python Scrips (.rpy) which are executed upon HTTP
requests
 It comes with proxy and reverse-proxy capabilities
 It supports Virtual Hosts
 • It can even serve Perl, PHP et cetera
What are Web Services?
Different books and different organizations provide different
definitions to Web Services. Some of them are listed here.

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
A web service is any piece of software that makes itself
available over the internet and uses a standardized
XML messaging system. XML is used to encode all
communications to a web service. For example, a client
invokes a web service by sending an XML message,
then waits for a corresponding XML response. As all
communication is in XML, web services are not tied to
any one operating system or programming language—
Java can talk with Perl; Windows applications can talk
with Unix applications.


Web services are self-contained, modular, distributed,
dynamic applications that can be described, published,
located, or invoked over the network to create
products, processes, and supply chains. These
applications can be local, distributed, or web-based.
Web services are built on top of open standards such
as TCP/IP, HTTP, Java, HTML, and XML.


Web services are XML-based information exchange
systems that use the Internet for direct application-to-
application interaction. These systems can include
programs, objects, messages, or documents.


A web service is a collection of open protocols and
standards used for exchanging data between
applications or systems. Software applications written
in various programming languages and running on
various platforms can use web services to exchange
data over computer networks like the Internet in a
manner similar to inter-process communication on a
single computer. This interoperability (e.g., between
Java and Python, or Windows and Linux applications) is
due to the use of open standards.

To summarize, a complete web service is, therefore, any


service that −

Is available over the Internet or private (intranet)
networks

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4

Uses a standardized XML messaging system


Is not tied to any one operating system or
programming language


Is self-describing via a common XML grammar


Is discoverable via a simple find mechanism

Components of Web Services


The basic web services platform is XML + HTTP. All the
standard web services work using the following components


SOAP (Simple Object Access Protocol)


UDDI (Universal Description, Discovery and Integration)


WSDL (Web Services Description Language)

All these components have been discussed in the Web


Services Architecture chapter.

How Does a Web Service Work?


A web service enables communication among various
applications by using open standards such as HTML, XML,
WSDL, and SOAP. A web service takes the help of −

XML to tag the data


SOAP to transfer a message


WSDL to describe the availability of service.

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
You can build a Java-based web service on Solaris that is
accessible from your Visual Basic program that runs on
Windows.

You can also use C# to build new web services on Windows


that can be invoked from your web application that is based
on JavaServer Pages (JSP) and runs on Linux.

Example
Consider a simple account-management and order
processing system. The accounting personnel use a client
application built with Visual Basic or JSP to create new
accounts and enter new customer orders.

The processing logic for this system is written in Java and


resides on a Solaris machine, which also interacts with a
database to store information.

The steps to perform this operation are as follows −



The client program bundles the account registration
information into a SOAP message.


This SOAP message is sent to the web service as the
body of an HTTP POST request.


The web service unpacks the SOAP request and
converts it into a command that the application can
understand.


The application processes the information as required
and responds with a new unique account number for
that customer.

Next, the web service packages the response into


another SOAP message, which it sends back to the
client program in response to its HTTP request.

The client program unpacks the SOAP message to


obtain the results of the account registration process.

R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4

R.JAYAPRABA M.C.A.,M.PHIL

You might also like