Unit - 2 Aggregate Data Types
Unit - 2 Aggregate Data Types
P
• Using tuples and ranges
PP
• Text sequence type: str
• Operations on strings
Sequence Types
• A sequence is a data type that represents a group of
elements. It is like an array in other languages.
• It stores and process a group of elements.
• strings, lists, tuples, range and dictionary are sequence
data type.
P
• List :
PP
• It consists of a group of elements or items.
• It can store different types of elements.
• E.g.
numbers = [ 1, 2, 3, 4, 5]; print(numbers)
names = [ 'Jay', 'khyati', 'Aakash', 'Mahi' ]; print(names)
num_name = [ 1, 'Jay', 2, 'Khyati' ]; print(num_name)
stud_info =[ 1 , 'Kamlesh', 'Male', 90, 85, 95 ]; print(stud_info)
Sequence Types
• List : To access the specific element in list use index
in capital bracket. E.g.
numbers = []
print('No. of elements in list' , len(numbers))
numbers = [ 1, 2, 3, 4, 5];
P
print('No. of elements in list' , len(numbers))
PP
print('Values of all elements of list:', numbers)
print('First element in list.'); print(numbers[0])
print('Second element in list.'); print(numbers[1])
print('last element in list.'); print(numbers[len(numbers)-1])
Sequence Types
a = [1,2,3,4,5]
print(a)
print(a[0])
print(a[1])
P
l1 = len(a) PP
print('Length of list a::',l1)
for i in range(l1):
print('Element at positoin [' +str(i)+']::-->',end=' ')
print(a[i])
print()
Sequence Types
a = [1,2,3,4,5]
print(a)
print('a[0:len(a):1]' , a[0:len(a):1])
P
print('a[0:len(a):2]',a[0:len(a):2])
PP
print('a[0:3:2]',a[0:3:2])
print('a[1:len(a):1]',a[1:len(a):1])
print('a[2:len(a):1]',a[2:len(a):1])
print('a[2:4:1]',a[2:4:1])
print('a[2:5:1]',a[2:5:1])
print('a[2:1:1]',a[2:1:1])
Sequence Types
a = [1,2,3,4,5]
print(a)
P
a.append(6)
a.append(7) PP
print('List after append data::',a)
P
numbers = [ 1, 2, 3, 4, 5];
print('All elements in list.'); print(numbers[ : : ]);
PP
print('Third ele. onwards in the list.'); print(numbers[2::]);
print('Third ele. onwards in the list.'); print(numbers[2:])
print('Third ele. onwards in the list.'); print(numbers[2::1]);
print('Alternate elements in the list.'); print(numbers[::2]);
print('Alternate elements in list.'); print(numbers[0::2]);
print('First four elements in list.'); print(numbers[0:4:1]);
print('First four elements in list.'); print(numbers[:4])
print('Alternate in first four elements.'); print(numbers[0:4:2 ]);
print('3rd and 4th element in list.'); print(numbers[2:4])
Sequence Types
P
PP
Sequence Types
List : Methods to process list:
numlist = [10,20,30,40,50]
n = len(numlist)
print(numlist)
print('Lenth of list is ',n)
P
numlist.append(60)
print('After append 60 in list :: ',numlist)
PP
# insert new element with value 5 at 0th position
numlist.insert (0,5)
print('After insert value 5 at 0th position :: ', numlist)
numlist2 = numlist.copy()
numlist.extend(numlist2)
print('After concate the copy of numlist :: ',numlist)
Sequence Types
List : Methods to process list:
numlist = [10,20,30,40,50,60,70,50]
N = numlist.count(50)
print(' No. of times 50 value comes in list',N)
numlist.remove(50)
P
print('After removing first occurance of 50 from a list :: ',numlist)
numlist.pop()
PP
print('After apply pop operation on list :: ',numlist)
numlist.sort()
print('After apply sort operation on list :: ',numlist)
numlist.reverse()
print('reverse the list :: ',numlist)
numlist.clear()
print('After clear the list :: ',numlist)
Sequence Types
List : Negative Index in List [start, stop, stepsize]
numlist = [10,20,30,40,50,60,70,80]
print('All elements in the list numlist::',numlist)
print(' Last element in the list numlist[-1]::',numlist[-1])
print(' Second last element in the list numlist[-2]::',numlist[-2])
print(' All elements in reverse order numlist[::-1]::',numlist[::-1])
print(' Null List numlist[:-1:-1]::',numlist[:-1:-1])
P
print(' Last element in the List numlist[:-2:-1]::',numlist[:-2:-1])
print(' Last two elements in the List numlist[:-3:-1]::',numlist[:-3:-1])
PP
print(' Last three elements in the List numlist[:-4:-1]::',numlist[:-4:-1])
print(' Last five elements in the List numlist[:-6:-1]::',numlist[:-6:-1])
print(' Elements at distance 3 in last five elements numlist[:-6:-2]::',numlist[:-6:-2])
print(' Elements at distance 3 in last five elements numlist[:-6:-3]::',numlist[:-6:-3])
print(' Elements in reverse order at distance of 2 numlist[::-2]::',numlist[::-2])
print(' Elements in reverse order at distance of 3 numlist[::-3]::',numlist[::-3])
print(' Elements at distance of 2 start from second last element numlist[-2::-2]::')
print(numlist[-2::-2])
print(' Elements at distance of 2 start from third last element numlist[-3::-2]::')
print(numlist[-3::-2])
Sequence Types
List :
Finding biggest and smallest element in list
numlist = [10,20,30,40,50,60,70,50]
max = max(numlist)
print(' Maximum value in list',max)
P
min = min(numlist)
print(' Minimum value in list',min)
PP
Program: To find the max and min value from list without using
functions.
Program: To find how many times an element occurred in the list.
Sequence Types
List :
Finding common elements in two lists
numlist1 = [10,20,30,40,50]
numlist2 = [10,200,300,400,500]
P
#convert lists into sets
set1 = set(numlist1)
PP
set2 = set(numlist2)
#find intersection of two sets
set3 = set1.intersection(set2)
#convert set into a list
newlist = list(set3)
print(newlist)
Sequence Types
List :
Nested list
nestlist = [ [1,2,3], [4,5,6], [7,8,9]]
print(nestlist)
#display row by row
P
for r in nestlist:
print( r )
PP
#display column in each row
for r in nestlist:
for c in r: #display column in each row
print(c, end= ' ')
print()
Program : Addition of two matrices.
Sequence Types
Tuple : Tuples are immutable. Once we create tuple we cannot
change its elements. It should be used to store data which should
not be modified and retrieve that data on demand.
tuple1 = ()
print(' Empty tuple ::',tuple1)
P
tuple2 = (10)
print('tuple with single element::',tuple2)
PP
tuple3 = (10,20,30,40,50)
print('tuple with only one type of elements::',tuple3)
tuple4 = (1,'Ramesh','Software Engineer',20000)
print('tuple with different types of elements::',tuple4)
tuple5 = 1,2,3,4,5
print('tuple with no braces for elements::',tuple5)
Sequence Types
Tuple : Accessing tuple elements
tuple1 = (10,20,30,40,50)
print('All elements of tuple::',tuple1)
print('First element of tuple ::' ,tuple1[0])
print('Third element of tuple ::' ,tuple1[2])
P
print('Last element of tuple ::' ,tuple1[-1])
PP
print('Third last element of tuple ::' ,tuple1[-3])
print('All elements of tuple ::' ,tuple1[ : ])
print('2nd and 3rd element of tuple ::' ,tuple1[1 : 3])
print('To extract alternate element ::' ,tuple1[ :: 2])
print('To extract alternate element in reverse order:' ,tuple1[ :: -2])
print('All elements start with 4th position from the rightside.::'
,tuple1[-4::-1])
Sequence Types
Tuple : Basic operation on tuples
student = (1,'Ajay',20,30,40)
print('Length of tuple::', len(student))
tpl = (1,2,3)
P
tpl1 = tpl * 3 #repeat the tuple 3 times.
print(tpl1)
PP
#concatenation of two tuple
ctuple = student + tpl
print(ctuple)
#if Ajay is member of tuple or not.
name='Ajay'
print(name in ctuple)
Sequence Types
Tuple : Function to process tuples
P
max() max(tpl) Returns the biggest element in the tuple
count() tpl.count(x) Returns how many times x comes in tuple
index() PP
tpl.index(x) Returns the first occurances of the
element 'x' in the tuple
sorted() sorted(tpl) Returns the elements in ascending order.
sorted(tpl, reverse=True) descending order
Sequence Types
Tuple :
Program: Apply various function on tuple.
tuple1 = (1,2,3,4,5,3,10,3,7,3)
print('Elements of tuple::' , tuple1)
print('length of tuple::' , len(tuple1))
P
print('Min value in tuple::',min(tuple1))
print('Max value in tuple::',max(tuple1))
PP
print('First occurances of 3 in tuple at index no.::',tuple1.index(3))
print('No. of occurances of 3 in tuple::',tuple1.count(3))
print('Sorted data in tuple::',sorted(tuple1))
print('Sorted data in descending order in tuple::', sorted(tuple1,
reverse=True))
Sequence Types
Tuple :
To accept multiple elements from the keyboard we use eval function
num = eval(input('Enter elements in ():'))
• It is used to evaluate whether the typed elements are a list or a tuple
depending upon the format of brackets given while typing the
elements.
P
• If we type the elements inside the square braces as: [1,2,3] then
PP
they are considered as elements of a list.
• If we type the elements inside the small braces as: (1,2,3) then they
are considered as elements of a tuple.
• If we do not type brackets, then by default they are taken as
elements of tuple.
Sequence Types
Tuple :
Program: Accept N numbers from users and find their sum and
average.
num = eval(input('Enter Numbers separated by commas:'))
print(type(num)) #num is a tuple or list object
P
sum=0
n=len(num)
PP
for i in range(n):
sum = sum + num[i]
print('Sum of numbers',sum)
print('Average of numbers',sum/n)
Sequence Types
Tuple :
Nested tuple : A tuple inserted insider another tuple is called nested
tuple. E.g.
tuple1 = (1,2,3,4,(5,6))
print('Nested tuple::',tuple1[4])
P
#Program: To sort a tuple with nested tuples.
emp=((1,'Sumit',40000),(2,'Jay',20000),(3,'Bina',30000))
PP
print('sort by default on id::',sorted(emp))
print('sorted by reverse on id::',sorted(emp,reverse=True))
print('sorted by name::',sorted(emp,key=lambda x:x[1]))
print('sorted by salary::',sorted(emp,key=lambda x:x[2]))
Sequence Types
Tuple :
Program: Inserting a new element in a tuple at particular index
tuple1 = (1,2,3,4,5,6)
print('Elements of tuple::',tuple1)
pos = int(input('Enter position number::'))
P
no = [int(input('Enter a new number::'))]
new_tuple = tuple(no) #New tuple with new element.
PP
# Copy from 0th to pos-1 elements into another tuple
result_tuple = tuple1[0:pos-1]
# Concatenate new element at pos-1
result_tuple= result_tuple + new_tuple
#concatenate the remaining elements of tuple1 from pos till end
result_tuple= result_tuple+tuple1[pos-1:]
print(result_tuple)
Sequence Types
List & Tuple
• They are both used to store collection of data
• They are both heterogeneous data types means that you can store
any kind of data type
• They are both ordered means the order in which you put the items
are kept.
P
• They are both sequential data types so you can iterate over the items
contained. PP
• Items of both types can be accessed by an integer index operator,
provided in square brackets, [index]
Sequence Types
Difference between tuple and list
P
PP
Sequence Types
Methods Tuple :
intersection(): A set contains only items that exist in both sets, or in all
sets if the comparison is done with more than two sets.
set.intersection(set1, set2 ... etc)
a={10,2,3,40}
P
b={10,20,30,40}
print(a.intersection(b))
PP
intersection_update(): A set contains only items that exist in both sets,
or in all sets if the comparison is done with more than two sets. Also
removes the unwanted items from the original set.
set.intersection_update (set1, set2 ... etc)
a={1,2,3,40}
b={10,20,30,40}
a.intersection_update (b); print(a);
Sequence Types
Methods Tuple :
difference : A set that contains the difference between two sets.
x.difference(y)
Return a set that contains the items that only exist in set x, and not in
set y:
P
a={10,2,3,40}; b={10,20,30,40};
print(a.difference(b))
PP
difference_update : A set that contains the difference between two
sets. x.difference_update (y)
Return a set that contains the items that only exist in set x, and not in
set y. Also removes the unwanted items from the original set.
a={10,2,3,40}; b={10,20,30,40};
a.difference_update(b);
print(a);
Sequence Types
Methods Tuple :
discard() : Removes the specified item from the set.
This method is different from the remove() method, because the
remove() method will raise an error if the specified item does not exist,
and the discard() method will not.
set.discard(value)
P
a={10,2,3,40}; a.discard(2); print(a);
PP
remove() : Removes the specified element from the set.
This method is different from the discard() method, because the
remove() method will raise an error if the specified item does not exist,
and the discard() method will not.
set.remove(item)
a={10,2,3,40}; a.remove(2); print(a);
Sequence Types
Tuples:: Methods
isdisjoint() : Return True if no items in set x is present in set y:
set.isdisjoint(set)
a={1,2,3,4}
b={10,20,30,40}
P
print(a.isdisjoint(b))
PP
issubset() method returns True if all items in the set exists in the
specified set, otherwise it retuns False.
set.issubset(set)
a={10,20}
b={10,20,30,40}
print(a.issubset(b))
Sequence Types
Tuples:: Methods
issuperset() method returns True if all items in the specified set exists in
the original set, otherwise it retuns False.
a={10,20,30,40}
b={10,20}
P
print(a.issuperset(b))
PP
pop() method removes a random item from the set.
set.pop()
a={10,20,30,40}
a.pop()
print(a)
Sequence Types
Tuples:: Methods
symmetric_difference() method returns a set that contains all items
from both set, but not the items that are present in both sets.
set.symmetric_difference(set)
P
a={10,20,300,400}; b={10,20,1,2,};
print(a.symmetric_difference(b))
PP
symmetric_difference_update() method updates the original set by
removing items that are present in both sets, and inserting the other
items.
set.symmetric_difference_update(set)
a={10,20,300,400}; b={10,20,1,2,};
print(a.symmetric_difference_update(b))
print(a); print(b);
Sequence Types
Tuples:: Methods
union() method returns a set that contains all items from the original
set, and all items from the specified set(s).
If an item is present in more than one set, the result will contain only
one appearance of this item.
set.union(set1, set2...)
P
a = {1,2,3,4}
b = {1,20,30,40}
PP
c = {1,200,3,40}
result = a.union(b, c)
print(result)
Sequence Types
Tuples:: Methods
update() method updates the current set, by adding items from another
set (or any other iterable).
If an item is present in both sets, only one appearance of this item will
be present in the updated set.
P
a={10,20,300,400}
b={10,20,1,2,}
print(a.update(b))
PP
print(a)
print(b)
Sequence Types
Range :
The range() function returns a sequence of numbers, starting from 0 by
default, and increments by 1 (by default), and stops before a specified
number.
Syntax:
range(start, stop, step)
P
start Optional. PP
An integer number specifying at which position to start. Default is 0
stop Required.
An integer number specifying at which position to stop (not included).
step Optional.
An integer number specifying the incrementation. Default is 1
Sequence Types
Range E.g.
for i in range (5) :
print(i);
print('\n');
for i in range (0,5) :
P
print(i);
print('\n');
for i in range(1,5): PP
print(i, end = " ");
print('\n');
for i in range(1,10,2):
print(i);
for i in range(10,5,-1):
print(i);
Sequence Types
String :
• Strings in python are surrounded by either single quotation marks, or
double quotation marks. 'hello' is the same as "hello".
• Assigning a string to a variable is done with the variable name
followed by an equal sign and the string:
str = "Hello"
P
print(str)
PP
• Python does not have a character data type, a single character is
simply a string with a length of 1. Square brackets can be used to
access elements of the string.
str = "Hello, World!"; print('First character :',str[0]);
print('Second character :',str[1]); print('Third character :',str[2])
• Loop through the each element ( or character) in a string.
for x in "computer":
print(x)
String : Sequence Types
Indexing : Index represents the position number. Index is written using
square braces [].
• By specifying the positon number through an index, we can refer to the
individual elements( or characters) of a string.
• For example
str[0] refers to the oth element of the string and
P
str[1] refers to the 1st element of ths string.
PP
Thus, str[i] can be use to refer to ith element of the string.
• When we use index as a negative number, it refers to elements in the
reverse order.
• Thus str[-1] refers to the last element and str[-2] refers to second last
element.
Sequence Types
String : Escape characters used in string
P
PP
str = 'Welcome \t to python \n programming'
print (str)
# To nullify the effect of escape character by adding r before the string
str = r'Welcome \t to python \n programming'
print (str)
String : Sequence Types
E.g.
str = "Hello, World"
print('First 4 characters of string ::',str[:4:])
print('Alternate character of first 4 characters ::',str[:4:2])
print('string in reverse order ::',str[::-1])
P
print('alternate character in reverse order ::',str[::-2])
print('Last characters of string::',str[-1::])
PP
print('Second last characters of string::',str[-2:-1:])
print('Third last characters of string::',str[-3:-2:])
print('Last 4 characters of string::',str[-4::])
String : Sequence Types
String concatenation is a process when one string is merged with
another string. It can be done in the following ways.
Using + operators
Using join() method
Using % method
P
Using format() function
Concatenation of strings: We can use '+' operator.
E.g.
str1 = 'Core'
PP
str2='Python'
str3 = str1 + str2
print(str3)
str3 = str1 + ' ' + str2
print(str3)
String : Sequence Types
# Python program to string concatenation using join() method.
str1 = "Hello"
str2 = "How are you?"
# join() method is used to combine the string with a separator Space(" ")
P
#Takes all items in an iterable and joins them into one string.
#string must be specified as separator(# sign)
PP
print("#".join(str2))
P
# Python program to string concatenation using format function
str1 ="Hello"
PP
str2 ="How are you?"
print("{} {}".format(str1,str2))
# store the result in another variable
str3="{}{}".format(str1,str2)
print(str3)
Sequence Types
String :
Checking Membership.
To check a certain phrase or character is present in a string, we can use the
keyword in.
txt = "Apple - Think Different."
if "Think" in txt:
P
print("Yes, 'Think' is present.")
PP
if "expensive" not in txt:
print("No, 'Same' is NOT present.")
String : Sequence Types
Comparing : Relational operators like > , >=, < , <=, == or != operators to
compare two strings. They return Boolean value, i.e. Either True or False
depending on the strings being compared.
S1='boy'
S2='box'
if (S1==S2):
P
print('Both are same')
else: PP
print('Both are different')
if (S1 < S2):
print('S1 less than S2')
else:
print('S2 less than S1')
String Methods: Sequence Types
P
PP
String Methods: Sequence Types
P
PP
String Methods: Sequence Types
P
PP
String Methods: Sequence Types
P
PP
String Methods: Sequence Types
P
PP
String : Sequence Types
Removing spaces from a string :
rstrip() : removes the spaces from the right side of the string.
lstrip() : removes the spaces from the left side of the string.
strip() : removes the spaces from the both sides of the string.
S1=' Kapil '; S2 = 'Sharma'; S3=' M '
P
print('S1::',S1); print('S2::',S2); print('S3::',S3);
print('S1.lstrip()::',S1.lstrip())
PP
print('S1.rstrip()::',S1.rstrip())
print('S3.strip()::',S3.strip())
print('S1+S2::',S1+S2)
print('S1.lstrip()+S2::',S1.lstrip()+S2)
print('S1.rstrip()+S2::',S1.rstrip()+S2)
print('S1.strip()+' ' + S2+ ' ' +S3.strip())::',S1.strip()+' ' + S3.strip() + ' ' +S2)
String : Sequence Types
Finding substring :
• find(), rfind(), index() and rindex() methods to locate sub string.
• The find() & index() search the sub string from the beginning of the string.
• The rfind() & rindex() search for the sub string from right to left, i.e. in
reverse order.
• The find() method returns – 1 if the sub string is not found.
P
• The index() method returns 'Value Error' exception if the sub string is not
found.
PP
• The format of find method is :
originalstring.find(substring, beginning, ending)
P
print('Search string ::', Sub_str)
print('Search using find method::')
if (n == -1):
PP
n = S1.find(Sub_str,0,len(S1))
print('Sub string not found in the main string');
else: print('Sub string found in the main string at position no', n+1);
print('Search using rfind method::')
n = S1.rfind(Sub_str,0,len(S1))
if (n == -1): print('Sub string not found in the main string');
else: print('Sub string found in the main string at position no', n+1);
String : Sequence Types
Finding substring:
E.g.
S1 = 'This is your book. Where is mine?'
Sub_str='is'
n = S1.index(Sub_str,0,len(S1))
P
if (n == -1):
print('Sub string is not found in the main string')
else: PP
print('Sub string is found in the main string at position no', n+1)
n = S1.rindex(Sub_str,0,len(S1))
if (n == -1):
print('Sub string not found in the main string')
else:
print('Sub string found in the main string at position no', n+1)
String : Sequence Types
To display all positions of a sub string in a given string (Optimize Code)
str1 = 'This is your book. Where is mine?' # defining string
substr = "is" # defining substring
print("The original string is : " + str1) # printing original string
print("The substring to find : " + substr)# printing substring
flag = False #becomes True if sub string is found
n = len(str1)
P
pos = -1
while True:
if pos == -1:
break
PP
pos = str1.find(substr,pos+1,n)
if flag == False:
print('Sub string not found')
String : Sequence Types
Counting Substrings in a String:
count() method is used to count the number of occurrences of a sub string
in a main string. Format :
stringname.count(substring)
stringname.count(substring , beg , end)
P
E.g.
str = 'Fear leads to anger; anger leads to hatred; hatred leads to conflict;
PP
conflict leads to suffering.'
n = str.count('anger'); print('Original string ::',str);
print('anger repeat ', n ,'times in string')
n = str.count('to',0,len(str)); print(' to repeat ', n , 'times in string')
n = str.count('o',0,20)
print(' o reoeat ', n , 'times in the first 20 characters in original string ')
n = str.count('o',0,40)
print(' o repeat ', n , 'times in the first 40 characters in original string ')
String :
Sequence Types
Strings are immutable. It means its content cannot be changed.
s1='hello'
s2='how r u?' hello how r u?
print('Before modifying') s1 s2
P
print('Id of s1 ::' ,id(s1))
print('Id of s2 ::' ,id(s2))
s1 = s2 PP
print('After modifying') hello how r u?
P
print('Original string::',str)
s1=input('Search string: ')
PP
s2=input('Replacement string: ')
print('Search string::',s1)
print('Replacement string::',s2)
strnew = str.replace(s1,s2)
print('Replaced string ::', strnew)
String : Sequence Types
Splitting & Joining Strings:
The split() method is used to break the string into pieces.
The join() method is used to join the pieces into string.
E.g.
str=input('Enter numbers separated by space::')
P
lst = str.split(' ')
print('Each number ::')
for i in lst:
print(i)
PP
str = ('apple', 'banana', 'orange')
#join the string elements with hyphon sign
newstr= "-".join(str)
print('Join the strings with hyphon ::',newstr)
String : Sequence Types
Changing case of a string
capitalize(): Returns a string where the first character is upper case, and the rest is lower case.
casefold(): Returns a string where all the characters are lower case.
str='Python is the future‘; print('Original string ::',str)
print('Characters in upper case::',str.upper())
print('Characters in lower case::',str.lower())
print('Characters in casefold::',str.casefold())
P
print('Characters in swap case::',str.swapcase())
print('Characters in title case::',str.title())
PP
print('Characters in Capitalize::',str.capitalize())
P
str1 = "This is python"
print('Original string ::',str1)
PP
print(str1.startswith('This'))
print(str1.endswith('python'))
print(str1.startswith('These'))
String : Sequence Types
Sorting : Arrange the string in sorted order by using sort() method and
sorted() function.
sort function makes changes to the original sequence, while the sorted ()
function creates a new sequence type containing a sorted of the given
sequence. E.g.
str1='Python'
P
print('Original string ::',str1)
str1= sorted(str1)
PP
print('Sorted string::' , str1)
print('\nSorted string::')
str1.sort()
for i in str1:
print(i , end= ' ')
Sequence Types
Sorting String :
Sort N strings into alphabetical order.
str1 = []
n = int(input('How many strings::'))
for i in range(n):
P
print('Enter string ::', end=' ')
str1.append(input())
PP
print('Sorted strings::')
str1 = sorted(str1)
for i in str1:
print(i)
Sequence Types
String Methods:
isalnum()
isalpha()
isdigit()
islower()
P
isupper()
istitle()
isspace() PP
String : Sequence Types
String testing methods
E.g. To know the type of character entered by the user.
str1 = input('Enter a character ::')
ch = str1[0]
if ch.isalnum():
print('It is alphanumber(alphabet or numeric) character')
if ch.isalpha():
P
print('It is an alphabet')
if ch.isupper():
else:
PP
print('It is capital letter')
P
count1=count1+1
count2=count2+1
print(count1)
PP
print("The number of digits is:")
P
if(i==' '):
word=word+1
print(word)
PP
print("Number of words in the string:")
P
fillchar (optional) - padding character
PP
sentence = "Python is best"
new_string = sentence.center(20, '#')
print(new_string)
P
encode() : Encodes the string, using the specified encoding. If no
PP
encoding is specified, UTF-8 will be used.
The popular encodings being utf-8, ascii, etc.
string = 'python'
# default encoding to utf-8
string_utf = string.encode()
print('The encoded version is:', string_utf)
Sequence Types
String Methods:
expandtabs() method sets the tab size to the specified
number of whitespaces.
txt = "H\te\tl\tl\to"
x = txt.expandtabs(4)
P
print(x)
PP
Output: H e l l o
P
The placeholders can be identified using
PP
named indexes {price},
numbered indexes {0}, or
even empty placeholders {}.
txt1="name:{fname},age:{age}".format(fname="Jay",age= 36)
txt2 = "My name is {0}, I'm {1}".format("John",36)
txt3 = "My name is {}, I'm {}".format("John",36)
Sequence Types
String Methods:
format_map() method is an inbuilt function in Python, which
is used to return a dictionary key’s value.
string.format_map(z)
Here z is a variable in which the input dictionary is stored and
P
string is the key of the input dictionary.
E.g. PP
# input stored in variable a.
a = {'x':‘Amit', 'y':'Vyas'}
# Use of format_map() function
print("{x}'s last name is {y}".format_map(a))
P
between Unicode code points and characters.
• Unicode is an extension of ASCII that allows many more
PP
characters to be represented.
• Convert character to Unicode code point: ord()
• Convert Unicode code point to character: chr()
• Use Unicode code points in strings: \x, \u, \U
Sequence Types
String Methods:
for i in range(5):
print(ord(str(i))) #display unicode of character
str1='AaBb'
for i in str1:
P
print(ord(i)) #display unicode of character
PP
#display character of unicode.
print(chr(65)) #integer value
print(chr(0x41)) #hexadecimal value
str1 = "\u0041" #unicode for A
print(str1)
Sequence Types
String Methods:
isdecimal() method returns True if all the characters are decimals (0-9).
txt = "33"
print(txt.isdecimal())
Output : True
P
isdigit() method returns True if all the characters are digits (0-9),
otherwise False. PP
Exponents, like ², are also considered to be a digit.
P
"-1" and "1.5" are NOT considered numeric values, because -
PP
and the . are not numberic.
a = "\u0030" #unicode for 0
b = "\u00B2" #unicode for ²
c = "10km2“; d = "-1“; e = "1.5"
print(a.isnumeric()); print(b.isnumeric())
print(c.isnumeric()); print(d.isnumeric()); print(e.isnumeric())
Output: True True False False False
Sequence Types
String Methods:
isidentifier() method returns True if the string is a valid
identifier, otherwise False.
A string is considered a valid identifier if it only contains
alphanumeric letters (a-z) and (0-9), or underscores (_).
P
A valid identifier cannot start with a number, or contain any
spaces. PP
a = "MyFolder“; b = "Demo002“; c = "2bring“; d = "my demo"
print(a.isidentifier()); print(b.isidentifier())
print(c.isidentifier()); print(d.isidentifier())
P
ljust() method will left align the string, using a specified character (space
PP
is default) as the fill character.
string.ljust(length, character)
Character Optional. A character to fill the missing space (to the right of
the string). Default is " " (space).
txt = "banana"
print(txt.ljust(20, "O"))
Output : bananaOOOOOOOOOOOOOO
Sequence Types
String Methods:
rjust() method will right align the string, using a specified
character (space is default) as the fill character.
string.rjust(length, character)
P
txt = "banana“; PP
print(txt.rjust(20, "O"))
Output : OOOOOOOOOOOOOObanana
Sequence Types
String Methods:
zfill() method adds zeros (0) at the beginning of the string,
until it reaches the specified length.
If the value of the len parameter is less than the length of the
string, no filling is done.
P
PP
a = "hello "; b = "welcome to the jungle "; c = "10.000"
print(a.zfill(10)); print(b.zfill(10)); print(c.zfill(10))
Output :
0000hello
welcome to the jungle
000010.000
Sequence Types
String Methods:
maketrans() method returns a mapping table that can be
used with the translate() method to replace specified
characters.
string.maketrans(x, y, z)
P
x Required. If only one parameter is specified, this has to
PP
be a dictionary describing how to perform the replace. If two
or more parameters are specified, this parameter has to be a
string specifying the characters you want to replace.
y Optional. A string with the same length as parameter x.
Each character in the first parameter will be replaced with the
corresponding character in this string.
z Optional. A string describing which characters to
remove from the original string.
Sequence Types
String Methods:
Use a mapping table to replace many characters:
txt = "Hi Sam! "; x = "mSa"; y = "eJo"
mytable = txt.maketrans(x, y)
print(txt.translate(mytable))
P
Output : Hi Joe!
PP
The third parameter in the mapping table describes
characters that you want to remove from the string:
txt = "Good night Sam!"; x = "mSa"; y = "eJo"; z = "odnght"
mytable = txt.maketrans(x, y, z)
print(txt.translate(mytable))
Output : G i Joe!
Sequence Types
String Methods:
partition() method searches for a specified string, and splits
the string into a tuple containing three elements.
First element contains the part before the specified string.
Second element contains the specified string.
P
Third element contains the part after the string.
PP
string.partition(value)
If the specified value is not found, the partition() method
returns a tuple containing:
1 - the whole string,
2 - an empty string,
3 - an empty string:
Sequence Types
String Methods:
rpartition() method searches for the last occurrence of a
specified string, and splits the string into a tuple containing
three elements.
First element contains the part before the specified string.
P
Second element contains the specified string.
PP
Third element contains the part after the string.
string.rpartition(value)
If the specified value is not found, the rpartition() method
returns a tuple containing:
1 - an empty string,
2 - an empty string,
3 - the whole string:
Sequence Types
String Methods:
txt = "I could eat bananas all day"
x = txt.partition("apples"); print(x)
txt = "I could eat bananas all day"
x = txt.partition("bananas"); print(x)
P
txt = "I could eat bananas all day"
x = txt.rpartition("apples"); print(x)
PP
txt = "I could eat bananas all day"
x = txt.rpartition("bananas"); print(x)
Output:
('I could eat bananas all day', '', '')
('I could eat ', 'bananas', ' all day')
('', '', 'I could eat bananas all day')
('I could eat ', 'bananas', ' all day')
Sequence Types
String Methods:
splitlines() method splits a string into a list. The splitting is
done at line breaks.
string.splitlines(keeplinebreaks)
keeplinebreaks Optional. Specifies if the line breaks
P
should be included (True), or not (False). Default value is False
PP
Split the string, but keep the line breaks: