Dap M2-1
Dap M2-1
Dap M2-1
#triple quotes
Str3 = ( '''Good Evening''' )
print(Str3)
Output:
Hello Good Morning
Have a great day
Good Evening
Basic String Operations:
1) String Concatenation: Concatenation is the process of combining two
or more strings into a single unified string.
• In Python, this merging operation is achieved using the "+"
operator, which allows the joining of one or more strings to create a new
concatenated string.
Output:
HelloGoodMorningIamTrisha
2) The In Operator:
• The in operator of Python is a Boolean operator which takes two string
operands.
• It returns True, if the first operand appears as a substring in second
operand, otherwise returns False.
Example 1:
if 'ya' in "Veda Vyas":
print('Your string contains "ya"')
Output:
Your string contains "ya"
3) String Comparison: Basic comparison operators like less than(<), greater
than(>), equals(==) etc , can be applied on string objects.
• Such comparison results in a Boolean value True or False.
Example:
str1 = 'Vikram'
str2 = 'Ram'
print(str1 == str2)
Output:
False
4) Traversal through a string with a loop:
• Extracting every character of a string one at a time and then performing
some action on that character is known as Traversal.
• A string can be traversed either using while loop or using for loop in
different ways.
Example 1 using while loop:
str = "Roopa"
Index = 0
while index < len(str):
print( str[index], end = "\t" )
index += 1
Output:
R o o p a
Output:
j a c k f r u i t
Accessing Characters in String by Index Number:
• We can get at any single character in a string using an index specified in
square brackets.
• The index value must be an integer and starts at zero.
• The index value can be an expression that is computed.
Example:
str = “good morning”
c ha ra c te r g o o d m o r n i n g
inde x 0 1 2 3 4 5 6 7 8 9 10 11
Example:
str = "good morning"
print(str[5])
print(str[8])
print(str[1])
print(str[4])
print(str[11])
Output:
m
n
o
g
• Python supports negative indexing of string starting from the end of the
string as shown below
Example:
str = “good evening”
c ha ra c te r g o o d e v e n i n g
inde x -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Example:
str = "good evening"
print(str[-5])
print(str[-8])
print(str[-1])
print(str[-4])
print(str[-11])
Output:
e
g
n
o
String Slicing and Joining:
• A segment (or) a portion of a string is called as slice.
• Only required number of characters can be extracted from a string using
colon(:) symbol.
• The basic syntax for slicing a string is:
where,
start: the position from where it starts.
end: the position where it stops(excluding end position).
step: also known as stride, is used to indicate number of steps.
To be incremented after extracting first character.
• If start is not mentioned, it means that slice should start from the
beginning of the string.
• If the end is not mentioned, it indicates the slice should be till the end of
the string.
• If the both are not mentioned, it indicates the slice should be from
beginning till the end of the string.
Example: s = “abcdefghij”
Inde x 0 1 2 3 4 5 6 7 8 9
c ha ra c te rs a b c d e f g h i j
Re ve rse inde x -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Slic ing Re sult De sc riptio n
Co de
s[2:5] cde characters at indices 2, 3, 4
s[ :5] abcde first five characters
s[5: ] fghij characters from index 5 to the end
s[-2: ] ij last two characters
s[ : ] abcdefghij entire string
s[1:7:2] bdf characters from index 1 to 6, by twos
s[ : :-1] jihgfedcba a negative step reverses the string
String Methods:
1) s.upper(): This function is used to convert lower case string to upper
case.
Example:
st ="hello friends good afternoon"
x=st.upper()
print(x)
Output:
HELLO FRIENDS GOOD AFTERNOON
2) s.lower(): This function is used to convert upper case string to lower
case.
Example:
str='LIFE IS VERY BEAUTIFUL'
x=str.lower()
print(x)
Output:
life is very beautiful
3) s.count(): This function returns the number of times a specified value
occurs in a string.
Example:
txt = "I live jackfruit, jackfruit are my favorite fruit"
x = txt.count("fruit")
print(x)
Output:
3
4) s.find(): This function searches the string for a specified value and returns
the position of where it was found.
Example:
txt = "Hello, welcome to my India."
x = txt.find("India")
print(x)
Output:
21
5) s.swapcase():
Python String swapcase() method converts all uppercase
characters to lowercase and vice versa of the given string and returns it.
Example:
str = "hAvE a HaPpY DaY aHeAd"
y=str.swapcase()
print(y)
Output:
HaVe A hApPy dAy AhEaD
6) s.replace():
It returns a copy of the string where occurrences of a substring
are replaced with another substring.
Example:
str = "Good Vibes only"
v = str.replace("Good", "Positive")
print(v)
Output:
Positive Vibes only
Formatting Strings: String can be formatted in different ways, using:
format Operator
format() method
f-string
1) Format Operator:
• Here we use the modulo % operator. The modulo % is also known as the
“string-formatting operator”.
• This operator allows us to construct strings, replacing parts of the strings
with the data stored in variables.
Example:
print("Nature is very %s in winter" %('beautiful’))
Output:
Nature is very beautiful in winter
2) Format() method:
• Format() method was introduced for handling complex string formatting
more efficiently.
• Formatters work by putting in one or more replacement fields and
placeholders defined by a pair of curly braces { } into a string and calling
the str.format().
• The value we wish to put into the placeholders and concatenate with the
string passed as parameters into the format function.
This code is using {} as a placeholder and then we have called .format()
method on the ‘equal’ to the placeholder.
Example:
print('We all are {}.’ .format('equal’))
Output:
We all are equal.
3) F-string:
• Formatted strings or f-strings were introduced in Python 3.6.
• A f-string is a string literal that is prefixed with “f”.
• These strings may contain replacement fields, which are expressions
enclosed within curly braces{}.
• These expressions are replaced with their values.
• In this code, the f-string f”My name is {name}.” is used to replace the
value of the name variable into the string.
Example:
name = 'Veda'
print(f "My name is {name}.")
Output:
My name is Veda.
Lists: Lists are used to store collection of data (or) multiple items in a
single variable.
• List items are ordered, changeable, and allow duplicate values.
Ordered: When we say that lists are ordered, it means that the items have
a defined order and that order will not change.
If you add new items to a list, the new items will be placed at the end of
the list.
Changeable: The list is changeable, meaning that we can change, add,
and remove items in a list after it has been created .
Allow Duplicates: Since lists are indexed, lists can have items with the
same value.
Creating List:
• A Python list is generated in Python programming by putting all of the
items (elements) inside square brackets [ ], separated by commas.
• It can include an unlimited number of elements of various data types
(integer, float, string, etc.). It can also be created using the built-
in list() method.
Example:
# creating empty list
my_list = []
print(my_list)
# creating list using square brackets
lang = ['Python', 'Java', 'HTML', 'SQL’, 'JavaScript']
print('List of languages are:', lang)
Output:
[]
List of languages are: ['Python', 'Java', 'HTML', 'SQL', 'Javascript']
['Vedh', 25, 'Hunter', 260000]
['Values', [1, 2, 3], ['Marks']]
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
Basic List Operations:
1) Access Elements of a List:
• A Python lists Operations entries can be accessed using the indexes [0],
[1], etc.
• An element in a list with an index of n has an index of n-1 since the index
begins at 0.
• By defining the beginning and ending points of the range, we can specify
a range of indexes. A new list containing the items we requested will be
the return value when we specify a range.
• Negative indexing refers to beginning at the end. The numbers -1 and -2
denote the last and second-to-last items.
Example:
list=["Student", "Teacher", "Parent", 1, 5, 6, 8]
print(list[0])
print(list[2:5])
print(list[-1])
Output:
Student
['Parent', 1, 5]
8
2) List Sorting: The list’s elements can be sorted either ascending order or in
descending order.
Example:
list = ["Student", "Teacher", "Parent", "Friend"]
list.sort()
print(list)
Output:
['Friend', 'Parent', 'Student', 'Teacher']
3) Update Elements of a List:
Lists can be modified, therefore by utilizing the element’s index, we can update
the list’s elements.
Example:
list = [1, 'Apple', 'Subject', 75, True]
list[2] = 'Carrot'
print(list)
Output:
[1, 'Apple', 'Carrot', 75, True]
4) Remove Elements from a List: Using the remove function, we can
easily delete a list element.
Example:
list = ['School', 'College', 'Music', 'Games']
list.remove(‘School')
print(list)
Output:
['College', 'Music', 'Games']
Indexing and Slicing in Lists:
Indexing Lists:
In Python, every list with elements has a position (or) index. Each element
of the list can be accessed or manipulated by using the index number.
1)Positive Indexing:
• In positive the first element of the list is at an index of 0 and the
following elements are at +1 and as follows.
• In the below figure, we can see how an element is associated with its
index (or) position.
Example:
list= [5,2,9,7,5,8,1,4,3]
print(list[2])
print(list[5])
Output:
9
8
2) Negative Indexing:
• In negative indexing, the indexing of elements starts from the end of the
list. That is the last element of the list is said to be at a position at -1 and
the previous element at -2 and goes on till the first element.
• In the below figure, we can see how an element is associated with its
index or position.
Example:
list= [5,2,9,7,5,8,1,4,3]
print(list[-2])
print(list[-8])
Output:
4
2
Slicing List:
• In Python slice a list in order to access a range of elements in it. One
method is to utilize the colon as a simple slicing operator (:).
• The slice operator allows you to specify where to begin slicing, where to
stop slicing, and what step to take. List slicing creates a new list from an
old one.
Syntax:
List[Start : Stop : Step]
• Start refers to the index of the element which is used as a start of our
slice.
• Stop refers to the index of the element we should stop just before to finish
our slice.
• Step allows you to take each nth-element within a start:stop range.
Example:
list= [5,2,9,7,5,8,1,4,3,6]
print(list[0:6])
print(list[1:9:2])
print(list[-1:-5:-2])
Output:
[5, 2, 9, 7, 5, 8]
[2, 7, 8, 4]
[6, 4]
Built-in Functions Used on Lists:
1) len(list): len() returns the number of elements in the list.
Syntax:
len(list)
Example:
list1, list2 = [878,'revlon', 'zara'], [456, 'boat']
print ("First list length : ", len(list1))
print ("Second list length : ", len(list2))
Output:
First list length : 3
Second list length : 2
2) min(list): min() returns the elements from the list with minimum value.
Syntax:
min(list)
Example:
list1, list2 = ['xyz', 'zara', 'abc'], [456, 700, 200]
print ("min value element : ", min(list1))
print ("min value element : ", min(list2))
Output:
min value element : abc
min value element : 200
3) max(list): max() returns the elements from the list with maximum
value.
Syntax:
max(list)
Example:
list1, list2 = ['xyz', 'zara', 'abc'], [456, 700, 200]
print ("Max value element : ", max(list1))
print ("Max value element : ", max(list2))
Output:
Max value element : zara
Max value element : 700
4) list(seq): list() takes sequence types and converts them to lists. This is used
to convert a given tuple into list.
Syntax:
list( seq )
Example:
Tuple = (123, 'xyz', 'zara', 'abc’ )
List = list(Tuple)
print ("List elements are : ", List)
Output:
List elements are : [123, 'xyz', 'zara', 'abc']
List Methods:
1) append(): The append() method appends an element to the end of the list.
Syntax:
list.append(element)
Example:
a = ["royal enfield", "hunter450", "r15"]
b = ["Ford", "BMW", "Volvo"]
a.append(b)
print(a)
Output:
['royal enfield', 'hunter450', 'r15', ['Ford', 'BMW', 'Volvo']]
2) count(): The count() method returns the number of elements with the
specified value.
Syntax:
list.count(value)
Example:
num = [1, 4, 8, 2, 9, 7, 8, 9, 3, 1, 8]
x = num.count(8)
print(x)
Output:
3
3) insert(): The insert() method inserts the specified value at the specified
position.
Syntax:
list.insert(pos, element)
Example:
fruits = ['apple', 'gauva', 'grapes']
fruits.insert(2, "jackfruit")
print(fruits)
Output:
['apple', 'gauva', 'jackfruit', 'grapes']
4) remove(): The remove() method removes the first occurrence of the
element with the specified value.
Syntax:
list.remove(element)
Example:
fruits = ['apple', 'grapes', 'blue berry']
fruits.remove("apple")
print(fruits)
Output:
['grapes', 'blue berry']
5) reverse(): The reverse() method reverses the order of the elements.
Syntax:
list.reverse()
Example:
colors = ['blue', 'lavender', 'black', 'green']
colors.reverse()
print(colors)
Output:
['green', 'black', 'lavender', 'blue']
Sets: Sets are used to store multiple items in a single variable.
• A set is a collection which is unordered, unchangeable, and unindexed.
• Sets are written with curly brackets { }.
Unordered: Unordered means that the items in a set do not have a defined
order.
Duplicates not allowed: Sets cannot have two items with the same value.
Example:
set = {"MCA", "MBA", "M.com", "MSc", "MCA"}
print(set)
Output:
{'MBA', 'MCA', ‘M.com', 'MSc'}
Tuples: Tuples are used to store multiple items in a single variable.
• A Tuple is a collection which are ordered, unchangeable, and allow duplicate
values.
• Tuples are written with round brackets ( ).
Ordered: Tuples are ordered, it means that the items have a defined order,
and that order will not change.
Unchangeable: Tuples are unchangeable, meaning that we cannot change,
add or remove items after the tuple has been created.
Allow Duplicates: Since tuples are indexed, they can have items with the
same value
Example:
tuple = ("Black", "Blue", "Purple", "Green", "Purple")
print(tuple)
Output:
('Black', 'Blue', 'Purple', 'Green', 'Purple')
Dictionaries: Dictionaries are used to store data values in
key: value pairs.
• A dictionary is a collection which is ordered, changeable and do not allow
duplicates.
• Dictionaries are written with curly brackets and have keys and values.
Ordered: Dictionaries are ordered, it means that the items have a defined
order, and that order will not change.
Changeable: Dictionaries are changeable, meaning that we can change, add
or remove items after the dictionary has been created.
Duplicates Not Allowed: Dictionaries cannot have two items with the same
key.
Example:
dict = {
"brand": "Hunter",
"model": 450,
"year": 2023
}
print(dict)
Output:
{'brand': 'Hunter', 'model': 450, 'year': 2023}
Files:
• File is a named location on disk to store related information.
• Data for python program can come from different sources such as
keyboard, database.
• Files are one such sources which can be given as input to the python
program. Hence handling files in right manner is very important.
• Primarily there are two types of files
Text files: A text file can be thought of as a sequence of lines without any
images, tables etc. These files can be created by using some text editors.
Binary files: These files are capable of storing text, image, video, audio,
database files etc which contains the data in the form of bits.
Opening files:
• To perform read (or) write operation on a file, first file must be opened.
• Opening the file communicates with the operating system, which knows
where the data for each file is stored.
• A file can be opened using a built-in function open( ).
f = open(“filename”,”mode”)
The following mode is supported:
1. r: open an existing file for a read operation.
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.
Reading Files:
Python.txt
Output:
Python is a high level programming language it is introduced by Guido van
rossam.
Python is easy to learn and simple to code an application
Example for appending and overwrite the content:
Appending File:
f = open("Python.txt", "a")
f.write("Python is also called as high level programming language")
f.close()
Output:
Woops! I have deleted the content!
Class:
• Class is a blueprint for creating object.
• A Class is a user-defined data type which binds data and function into a
single unit.
• A class can have a set of variables( attributes) and member
functions( known as methods).
• An object is an instance of a class. One can create any number of objects
for a class.
• To create a class, use the keyword class.
Syntax for creating class:
class ClassName:
# Statement
obj = ClassName()
print(obj.atr)
Example for Class and object:
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
Output:
5
Constructors: Python facilitates a special type of method, also called as
Python Constructors.
• Constructors are generally used for instantiating an object.
• The task of constructors is to initialize(assign values) to the data members
of the class when an object of the class is created.
def __init__(self):
# body of the constructor
Features of Python Constructors:
def details(self):
print("Employee Name : ", self.Name)
print("Employee Salary: ", self.Salary)
print( "\n" )
first = Employees("Veda", 87000)
second = Employees("Shreya", 80000)
third = Employees("Shree", 70000)
fourth = Employees(“Rithu", 30000)
fifth = Employees("Lucky", 40000)
first.details()
second.details()
third.details()
fourth.details()
fifth.details()
Output:
Employee Name : Veda
Employee Salary: 87000
Inheritance Syntax:
Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}
Example Program:
class Person(object): #Parent class
# Constructor
def __init__(self, name, id):
self.name = name
self.id = id
# An Object of Person
emp = Person("Rekha", 102)
emp.Display()
#child class
class Employee(Person):
def Print(self):
print("Emp class called")
Rekha 102
Prohana 103
Emp class called
Method Overloading:
Two (or) more methods have the same name but
different numbers of parameters (or) different types of parameters. These
methods are called overloaded methods and this is called method overloading.
• The problem with method overloading in Python is that we may overload
the methods but can only use the latest defined method.
Example Program: 1st Method
def product(a, b):
p=a*b
print(p)
# Second product method Takes three argument and print their product
def product(a, b, c):
p=a*b*c
print(p)
# Uncommenting the below line shows an error
# product(4, 5)
# This line will call the second product method
product(4, 5, 5)
Output:
100
Example: 2nd Method
class Main:
def sum(self, x1= None, x2= None, x3= None):
if x3 is None:
print('Sum of two numbers: ', x1+x2)
else:
print('Sum of three numbers: ', x1+x2+x3)
m = Main()
m.sum(10, 20) # calling sum with 2 parameters
m.sum(10, 20, 30) # calling same method with 3 parameters
Output:
Sum of two numbers: 30
Sum of three numbers: 60
Thank You