PFSD stringFuncLIST
PFSD stringFuncLIST
UNIT-4
Hibernate
String datatype
What is String?
Any sequence of characters within either single quotes or double quotes is
considered as a
String.
Syntax:
s = ‘red'
s = “line"
How to define multi-line String Literals?
We can define multi-line String literals by using triple single or double quotes.
Eg:
>>> s = '‘gojo
Is
dead'''
We can also use triple quotes to use single quotes or double quotes as symbol
inside
String literal.
How to Access Characters of a String?
Syntax: s[beginindex:endindex:step]
Note: If we are not specifying bEgin index then it will consider from bEginning
of the string.
If we are not specifying end index then it will consider up to end of the string.
The default value for step is 1
Behaviour of Slice Operator:
1) s[bEgin:end:step]
2) Step value can be either +ve or –ve
3) If +ve then it should be forward direction(left to right) and we have to consider
bEgin
to end-1
4) If -ve then it should be backward direction (right to left) and we have to consider
bEgin
to end+1.
***Note:
In the backward direction if end value is -1 then result is always empty.
In the forward direction if end value is 0 then result is always empty.
In Forward Direction:
default value for bEgin: 0
default value for end: length of string
default value for step: +1
In Backward Direction:
default value for bEgin: -1
default value for end: -(length of string+1)
Note: Either forward or backward direction, we can take both +ve and -ve values
for
bEgin and end index.
Mathematical Operators for String:
Note: 1) To use + operator for Strings, compulsory both arguments should be str
type. 2) To use * operator for Strings, compulsory one argument should be str
and other argument should be int.
len() in-built Function:
We can use len() function to find the number of characters present in the string.
Eg:
s = 'durga'
print(len(s)) – 5
Checking Membership:
We can check whether the character or string is the member of another string or
not by
using in and not in operators
s = 'durga'
print('d' in s) True
print('z' in s) False
Comparison of Strings:
We can use comparison operators (<, <=, >, >=) and equality operators (==, !
=) for
strings.
Comparison will be performed based on alphabetical order
Removing Spaces from the String:
We can use the following 3 methods
1) rstrip() To remove spaces at right hand side
2) lstrip() To remove spaces at left hand side
3) strip() To remove spaces both sides
Finding Substrings:
We can find the number of occurrences of substring present in the given string by
using
count() method.
1) s.count(substring) It will search through out the string.
2) s.count(substring, bEgin, end) It will search from bEgin index to end-1
1) s="abcabcabcabcadda"
2) print(s.count('a'))
3) print(s.count('ab'))
4) print(s.count('a',3,7))x
Replacing a String with another String:
s.replace(oldstring, newstring)
inside s, every occurrence of old String will be replaced with new String.
Eg 1:
s = "Learning Python is very difficult"
s1 = s.replace("difficult","easy")
print(s1)
Output: Learning Python Is very easy
Q) String Objects are Immutable then how we can change the Content by
using replace() Method
Splitting of Strings:
We can split the given string according to specified seperator by using split()
method.
l = s.split(seperator)
The default seperator is space. The return type of split() method is List.
1) s=“nothing changes if nothing changes"
2) l=s.split()
3) for x in l:
4) print(x)
Ask students
Joining of Strings:
We can join a Group of Strings (List OR Tuple) wrt the given Seperator.
s = seperator.join(group of strings)
Eg 1:
t = ('sunny', 'bunny', 'chinny')
s = '-'.join(t)
print(s)
Output: sunny-bunny-chinny
Changing Case of a String:
We can format the strings with variable values by using replacement operator {}
and
format() method.
1) name = ‘ben'
2) salary = 10000
3) age = 48
4) print("{} 's salary is {} and his age is {}".format(name,salary,age))
5) print("{0} 's salary is {1} and his age is {2}".format(name,salary,age))
6) print("{x} 's salary is {y} and his age is {z}".format(z=age,y=salary,x=name))
List datatype
If we want to represent a group of individual objects as a single entity where insertion
order preserved and duplicates are allowed, then we should go for List.
֍ insertion order preserved.
֍ duplicate objects are allowed.
֍ heterogeneous objects are allowed.
֍ List is dynamic because based on our requirement we can increase the size and
decrease the size.
֍ In List the elements will be placed within square brackets and with comma seperator.
֍ We can differentiate duplicate elements by using index and we can preserve insertion
order by using index. Hence index will play very important role.
֍ Python supports both positive and negative indexes. +ve index means from left to
right where as negative index means right to left.
[10,"A","B",20, 30, 10]
Creation of List Objects:
1) s=“unaagii"
2) l=list(s)
3) print(l)
['u', 'n', 'a', 'a', 'g', 'i', 'i']
4)With split()
1) s="Learning Python is very very easy !!!"
2) l=s.split()
3) print(l)
4) print(type(l))
['Learning', 'Python', 'is', 'very', 'very', 'easy', '!!!‘]
We can access elements of the list either by using index or by using slice
operator(:)
1)By using Index:
֍ List follows zero based index. ie index of first element is zero.
֍ List supports both +ve and -ve indexes.
֍ +ve index meant for Left to Right
֍ -ve index meant for Right to Left
֍ list = [10, 20, 30, 40]
2)By using Slice Operator:
Syntax: list2 = list1[start:stop:step]
Start - It indicates the Index where slice has to Start
Default Value is 0
Stop - It indicates the Index where slice has to End
Default Value is max allowed Index of List ie Length of the List
Step - increment value
Default Value is 1
1) n=[1,2,3,4,5,6,7,8,9,10]
2) print(n[2:7:2])
3) print(n[4::2])
4) print(n[3:7])
5) print(n[8:2:-2])
6) print(n[4:100])
Output
[3, 5, 7]
[5, 7, 9]
[4, 5, 6, 7]
[9, 7, 5]
[5, 6, 7, 8, 9, 10]
List vs Mutability:
Once we creates a List object, we can modify its content. Hence List objects are
mutable.
1) n=[10,20,30,40]
2) print(n)
3) n[1]=777
4) print(n)
D:\Python_classes>py test.py
[10, 20, 30, 40]
[10, 777, 30, 40]
Traversing the Elements of List:
1)By using while Loop:
1) nl = [0,1,2,3,4,5]
2) i = 0
3) while i < len(nl):
4) print(nl[i])
5) i=i+1
Output:
0
1
2
3
4
5
1)By using for Loop:
1) nl = [0,1,2,3,4,5]
2) for i in nl:
3) print (i)
Important Functions of List:
1) len():
Returns the number of elements present in the list
Eg: n = [10, 20, 30, 40]
print(len(n) - 4
2) count():
It returns the number of occurrences of specified item in the list
1) n=[1,2,2,2,2,3,3]
2) print(n.count(1))
3) print(n.count(2))
4) print(n.count(3))
5) print(n.count(4))
D:\Python_classes>py test.py
1
4
2
0
3) index():
Returns the index of first occurrence of the specified item.
1) n = [1, 2, 2, 2, 2, 3, 3]
2) print(n.index(1)) 0
3) print(n.index(2)) 1
4) print(n.index(3)) 5
5) print(n.index(4)) ValueError: 4 is not in list
Note: If the specified element not present in the list then we will get ValueError.Hence
before index() method we have to check whether item present in the list or not by using
in operator.
print( 4 in n) - False
II. Manipulating Elements of List:
1) append() Function:
We can use append() function to add item at the end of the list.
1) list=[]
2) list.append("A")
3) list.append("B")
4) list.append("C")
5) print(list)
D:\Python_classes>py test.py
['A', 'B', 'C']
2) insert() Function:
To insert item at specified index position
1) n=[1,2,3,4,5]
2) n.insert(1,888)
3) print(n)
[1, 888, 2, 3, 4, 5]
1) n=[1,2,3,4,5]
2) n.insert(10,777)
3) n.insert(-10,999)
4) print(n)
[999, 1, 2, 3, 4, 5, 777]
3) extend() Function:
To add all items of one list to another list
l1.extend(l2)
all items present in l2 will be added to l1
1) order1=["Chicken","Mutton","Fish"]
2) order2=["RC","KF","FO"]
3) order1.extend(order2)
4) print(order1)
['Chicken', 'Mutton', 'Fish', 'RC', 'KF', 'FO']
1) order = ["Chicken","Mutton","Fish"]
2) order.extend("Mushroom")
3) print(order)
['Chicken', 'Mutton', 'Fish', 'M', 'u', 's', 'h', 'r', 'o', 'o', 'm']
4) remove() Function:
We can use this function to remove specified item from the list.If the item present
multiple times then only first occurrence will be removed.
1) n=[10,20,10,30]
2) n.remove(10)
3) print(n)
D:\Python_classes>py test.py
[20, 10, 30]
If the specified item not present in list then we will get ValueError
5) pop() Function:
It removes and returns the last element of the list.
This is only function which manipulates list and returns some element.
1) n=[10,20,30,40]
2) print(n.pop())
3) print(n.pop())
4) print(n)
40
30
[10, 20]
If the list is empty then pop() function raises IndexError
Note:
1) pop() is the only function which manipulates the list and returns some value
2) In general we can use append() and pop() functions to implement stack
datastructure
by using list,which follows LIFO(Last In First Out) order.
In general we can use pop() function to remove last element of the list. But we
can use to
remove elements based on index.
n.pop(index) To remove and return element present at specified index.
n.pop() To remove and return last element of the list
Note: List Objects are dynamic. i.e based on our requirement we can increase
and decrease the size.
append(), insert(), extend() -for increasing the size/growable nature
remove(), pop() - for decreasing the size /shrinking nature
III) Ordering Elements of List:
1) reverse():
We can use to reverse() order of elements of list.
1) n=[10,20,30,40]
2) n.reverse()
3) print(n)
D:\Python_classes>py test.py
[40, 30, 20, 10]
2)sort():
In list by default insertion order is preserved. If want to sort the elements of list
according to default natural sorting order then we should go for sort() method.
For numbers Default Natural sorting Order is Ascending Order
For Strings Default Natural sorting order is Alphabetical Order
1) n = [20,5,15,10,0]
2) n.sort()
3) print(n) - [0,5,10,15,20]
5) s = ["Dog","Banana","Cat","Apple"]
6) s.sort()
7) print(s) ['Apple','Banana','Cat','Dog']
Note: To use sort() function, compulsory list should contain only homogeneous
elements.
Otherwise we will get TypeError
1) n=[20,10,"A","B"]
2) n.sort()
3) print(n)
TypeError: '<' not supported between instances of 'str' and 'int'
Note: In Python 2 if List contains both numbers and Strings then sort() function first sort
numbers followed by strings
1) n=[20,"B",10,"A"]
2) n.sort()
3) print(n)# [10,20,'A','B']
But in Python 3 it is invalid.
To Sort in Reverse of Default Natural Sorting Order:
The process of giving another reference variable to the existing list is called aliasing.
1) x=[10,20,30,40]
2) y=x
3) print(id(x))
4) print(id(y))
The problem in this approach is by using one reference variable if we are changing
content, then those changes will be reflected to the other reference variable.
1) x = [10,20,30,40]
2) y = x
3) y[1] = 777
4) print(x)
- [10,777,30,40]
To overcome this problem we should go for cloning.
The process of creating exactly duplicate independent object is called cloning.
We can implement cloning by using slice operator or by using copy() function
1) By using Slice Operator:
1) x = [10,20,30,40]
2) y = x[:]
3) y[1] = 777
4) print(x) [10, 20, 30, 40]
5) print(y) [10, 777, 30, 40]
We can check whether element is a member of the list or not by using memebership
operators.
1) in Operator
2) not in Operator
1) n=[10,20,30,40]
2) print (10 in n)
3) print (10 not in n)
4) print (50 in n)
5) print (50 not in n)
Output
True
False
False
True
clear() Function:
We can use clear() function to remove all elements of List.
1) n=[10,20,30,40]
2) print(n)
3) n.clear()
4) print(n)
Output D:\Python_classes>
py test.py [10, 20, 30, 40] []
Nested Lists:
we can take one list inside another list. Such type of lists are called nested lists.
1) n=[10,20,[30,40]]
2) print(n)
3) print(n[0])
4) print(n[2])
5) print(n[2][0])
6) print(n[2][1])
Output
[10, 20, [30, 40]]
10
[30, 40]
30
40
Nested List as Matrix:
1) t = ()
Creation of Empty Tuple
2) t = (10,)
t = 10,
Creation of Single valued Tuple, Parenthesis are Optional, should ends with
Comma
3) t = 10, 20, 30
t = (10, 20, 30)
Creation of multi values Tuples & Parenthesis are Optional.
4) By using tuple() Function:
1) list=[10,20,30]
2) t=tuple(list)
3) print(t)
4)
5) t=tuple(range(10,20,2))
6) print(t)
Accessing Elements of Tuple:
1) s={10,20,30,40}
2) print(s)
3) print(type(s))
Output
{40, 10, 20, 30}
<class 'set'>
We can create set objects by using set() Function s = set(any sequence) Note:
֍ While creating empty set we have to take special care.
֍ Compulsory we should use set() function.
֍ s = {} It is treated as dictionary but not empty set
Important Functions of Set:
1) add(x):
Adds item x to the set.
1) s={10,20,30}
2) s.add(40);
3) print(s) #{40, 10, 20, 30}
2) update(x,y,z):
To add multiple items to the set.
Arguments are not individual elements and these are Iterable objects like List,
Range
etc.
All elements present in the given Iterable objects will be added to the set.
1) s={10,20,30}
2) l=[40,50,60,10]
3) s.update(l,range(5))
4) print(s)
Output: {0, 1, 2, 3, 4, 40, 10, 50, 20, 60, 30}
Which of the following are valid for set s?
1) s.add(10)
2) s.add(10,20,30)
3) s.update(10)
4) s.update(range(1,10,2),range(0,10,2))
Ask studnets
3) copy():
Returns copy of the set.
It is cloned object.
1) s = {10,20,30}
2) s1 = s.copy()
3) print(s1)
4) pop():
It removes and returns some random element from the set.
1) s={40,10,30,20}
2) print(s)
3) print(s.pop())
4) print(s)
Output
{40, 10, 20, 30}
40
{10, 20, 30}
5) remove(x):
It removes specified element from the set.
If the specified element not present in the Set then we will get KeyError.
1) s = {40, 10, 30, 20}
2) s.remove(30)
3) {40, 10, 20}
4) s.remove(50 )KeyError: ) 50
6) discard(x):
1) It removes the specified element from the set.
2) If the specified element not present in the set then we won't get any error.
1) s = {10, 20, 30}
2) s.discard(10)
7) clear():
To remove all elements from the Set.
1) s={10,20,30}
2) print(s)
3) s.clear()
4) print(s)
Output
{10, 20, 30}
set()
Mathematical Operations on the Set:
1) union():
x.union(y) - We can use this function to return all elements present in both sets
x.union(y) OR x|y.
1) x = {10, 20, 30, 40}
2) y = {30, 40, 50, 60}
3) print (x.union(y)) {10, 20, 30, 40, 50, 60}
4) print (x|y) {10, 20, 30, 40, 50, 60}
2) intersection():
x.intersection(y) OR x&y.
Returns common elements present in both x and y.
1) x = {10, 20, 30, 40}
2) y = {30, 40, 50, 60}
3) print (x.intersection(y)) {40, 30}
4) print(x&y) {40, 30}
3) difference():
x.difference(y) OR x-y.
Returns the elements present in x but not in y.
1) x = {10, 20, 30, 40}
2) y = {30, 40, 50, 60}
3) print (x.difference(y)) 10, 20
4) print (x-y) {10, 20}
5) print (y-x) {50, 60}
4)symmetric_difference():
x.symmetric_difference(y) OR x^y.
Returns elements present in either x OR y but not in both.
1) x = {10, 20, 30, 40}
2) y = {30, 40, 50, 60}
3) print (x.symmetric_difference(y)) {10, 50, 20, 60}
4) print(x^y) {10, 50, 20, 60}
4)symmetric_difference():
x.symmetric_difference(y) OR x^y.
Returns elements present in either x OR y but not in both.
1) x = {10, 20, 30, 40}
2) y = {30, 40, 50, 60}
3) print (x.symmetric_difference(y)) {10, 50, 20, 60}
4) print(x^y) {10, 50, 20, 60}
Membership Operators: (in, not in)
1) s=set("durga")
2) print(s)
3) print('d' in s)
4) print('z' in s)
Output
{'u', 'g', 'r', 'd', 'a'}
True
False
Set Comprehension:
Set comprehension is possible.
1) s = {x*x for x in range(5)}
2) print (s) {0, 1, 4, 9, 16}
3)
4) s = {2**x for x in range(2,10,2)}
5) print (s) {16, 256, 64, 4}
Set Objects won't support indexing and slicing:
1) s = {10,20,30,40} 2) print(s[0]) TypeError: 'set' object does not support
indexing 3) print(s[1:3]) TypeError: 'set' object is not subscriptable
Write a Program to eliminate Duplicates Present in the List
Approach - 1
1) l=eval(input("Enter List of values: "))
2) s=set(l)
3) print(s)
D:\Python_classes>py test.py
Enter List of values: [10,20,30,10,20,40]
{40, 10, 20, 30}
DICTIONARY DataType
֍ We can use List, Tuple and Set to represent a group of individual objects as a single
entity.
֍ If we want to represent a group of objects as key-value pairs then we should go for
Dictionary.
֍ Duplicate keys are not allowed but values can be duplicated.
֍ Hetrogeneous objects are allowed for both key and values.
֍ Insertion order is not preserved
֍ Dictionaries are mutable
֍ Dictionaries are dynamic
֍ indexing and slicing concepts are not applicable
How to Create Dictionary?
d = {} OR d = dict()
We are creating empty dictionary. We can add entries as follows
1) d[100]=“RED"
2) d[200]=“BLUE"
3) d[300]=“GREEN"
4) print(d) {100: ‘RED', 200: ‘BLUE’, 300: ‘GREEN'}
If we know data in advance then we can create dictionary as follows
d = {100:‘RED' ,200:‘BLUE', 300:' GREEN '}
d = {key:value, key:value}
How to Access Data from the Dictionary?
We can access data by using keys.
1) d = {100:‘ken',200:‘adams', 300:‘is'}
2) print(d[100]) #ken
3) print(d[300]) #is
print(d[400]) - KeyError: 400
We can prevent this by checking whether key is already available or not by using
has_key() function or by using in operator
.
d.has_key(400) - Returns 1 if key is available otherwise returns 0
But has_key() function is available only in Python 2 but not in Python 3. Hence
compulsory we have to use in operator.
if 400 in d:
print(d[400])
How to Update Dictionaries?
֍ d[key] = value
֍ If the key is not available then a new entry will be added to the dictionary with
the
specified key-value pair
֍ If the key is already available then old value will be replaced with new value.
1) d={100:“red",200:“red3",300:“red"}
2) print(d)
3) d[400]=“grey"
4) print(d)
5) d[100]=“black"
6) print(d)
1) del d[key]
It deletes entry associated with the specified key.
If the key is not available then we will get KeyError.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d)
3) del d[100]
4) print(d)
5) del d[400]
Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
{200: 'ravi', 300: 'shiva'}
KeyError: 400
2) d.clear()
To remove all entries from the dictionary.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d)
3) d.clear()
4) print(d)
1) dict():
To create a dictionary
d = dict() It creates empty dictionary
d = dict({100:"durga",200:"ravi"}) It creates dictionary with specified elements
d = dict([(100,"durga"),(200,"shiva"),(300,"ravi")])
It creates dictionary with the given list of tuple elements
2) len()
Returns the number of items in the dictionary.
4) get():
To get the value associated with the key
d.get(key)
If the key is available then returns the corresponding value otherwise returns
None.It
wont raise any error
d.get(key,defaultvalue)
If the key is available then returns the corresponding value otherwise returns default
value.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d[100]) durga
3) print(d[400]) KeyError:400
4) print(d.get(100)) durga
5) print(d.get(400)) None
6) print(d.get(100,"Guest")) durga
7) print(d.get(400,"Guest")) Guest
5) pop():
d.pop(key)
It removes the entry associated with the specified key and returns the
corresponding value.
If the specified key is not available then we will get KeyError.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d.pop(100))
3) print(d)
4) print(d.pop(400))
Output
durga
{200: 'ravi', 300: 'shiva'}
KeyError: 400
6) popitem():
It removes an arbitrary item(key-value) from the dictionaty and returns it.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d)
3) print(d.popitem())
4) print(d)
Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
(300, 'shiva')
{100: 'durga', 200: 'ravi'}
If the dictionary is empty then we will get KeyError
d={}
print(d.popitem()) ==>KeyError: 'popitem(): dictionary is empty
7) keys():
It returns all keys associated eith dictionary.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d.keys())
3) for k in d.keys():
4) print(k)
Output
dict_keys([100, 200, 300])
100
200
300
8) values():
It returns all values associated with the dictionary.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d.values())
3) for v in d.values():
4) print(v)
Output
dict_values(['durga', 'ravi', 'shiva'])
durga
ravi
shiva
9) items():
It returns list of tuples representing key-value pairs.
[(k,v),(k,v),(k,v)]
1) Output
100 -- durga
200 -- ravi
300 – shiva
10) copy():
To create exactly duplicate dictionary (cloned copy)
d1 = d.copy();
12) update():
d.update(x)
All items present in the dictionary x will be added to dictionary d
13) setdefault():
d.setdefault(k,v)
If the key is already available then this function returns the corresponding value.
If the key is not available then the specified key-value will be added as new item
to
the dictionary.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d.setdefault(400,"pavan"))
3) print(d)
4) print(d.setdefault(100,"sachin"))
5) print(d)
Output
pavan
{100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
durga
{100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'pavan'}