Python Module 2 Vtu
Python Module 2 Vtu
Python Module 2 Vtu
MODULE II
2.1 LISTS
The List Data Type, Working with Lists, List Methods , Augmented Assignment Operators, Example
Program: Magic 8 Ball with a List, List-like Types: Strings and Tuples, References,
The Dictionary Data Type, Pretty Printing, Using Data Structures to Model Real-World Things
Working with Strings, Useful String Methods, Project: Password Locker, Project: Adding Bullets to
Wiki Markup
MODULE II
2.1 LISTS
The List Data Type
A list is an ordered sequence of multiple values.
It is a data structure in Python.
The values inside the lists can be of any type (like integer, float, strings, lists, tuples,
dictionaries etc) and are called as elements or items.
A list value looks like this: ['cat', 'bat', 'rat', 'elephant'].
The elements of lists are enclosed within square brackets separated by commas.
For example,
ls1=[10,-4, 25, 13]
ls2=[“Tiger”, “Lion”, “Cheetah”]
Here, ls1 is a list containing four integers, and ls2 is a list containing three strings.
A list need not contain data of same type. We can have mixed type of elements in list.
For example,
ls3=[3.5, „Tiger‟, 10, [3,4]]
Here, ls3 contains a float, a string, an integer and a list.
This illustrates that a list can be nested as well.
or
>>> ls =list() #list() Constructor with zero arguments
>>> type(ls)
<class 'list'>
In fact, list() is the name of a method (special type of method called as constructor – which will be
discussed in Module 4) of the class list.
>>> type(ls)
<class „list‟>
A new list can be created using list() constructor and by passing arguments to it as shown below
>>> ls2=list([3,4,1]) #list() Constructor with arguments
>>> print(ls2)
[3, 4, 1]
List Indexing
The elements in the list can be accessed using a numeric index within square-brackets.
The integer inside the square brackets that follows the list is called an index.
The first value in the list is at index 0, the second value is at index 1, the third value is at index 2,
and so on.
In Python, we can have 2 types of indexing: Forward(Positive) and Backward(Negative) Indexing
as shown below:
Forward Indexing - Starts from index 0 from the beginning of the list moving towards the end.
Negative Indexing - Starts from index -1 from the end of the list moving towards the beginning.
>>> ls=[34, 'hi', [2,3],-5]
>>> print(ls[1])
hi
>>> print(ls[2])
[2, 3]
Observe here that, the inner list is treated as a single element by outer list. If we would like to
access the elements within inner list, we need to use double-indexing as shown below –
>>> print(ls[2][0])
2
>>> print(ls[2][1])
3
Note that, the indexing for inner-list again starts from 0.
Thus, when we are using double- indexing, the first index indicates position of inner list inside
outer list, and the second index means the position particular value within inner list.
Lists are mutable. That is, using indexing, we can modify any value within list after it is created.
In the following example, the 3rd element (i.e. index is 2) is being modified –
>>> ls=[34, 'hi', [2,3],-5]
>>> ls[2]='Hello'
>>> print(ls)
[34, 'hi', 'Hello', -5]
The list can be thought of as a relationship between indices and elements. This relationship is
called as a mapping. That is, each index maps to one of the elements in a list.
The index for extracting list elements has following properties –
Any integer expression can be an index.
>>> ls=[34, 'hi', [2,3],-5]
>>> print(ls[2*1])
[2,3]
Attempt to access a non-existing index will throw and IndexError.
>>> ls=[34, 'hi', [2,3],-5]
>>> print(ls[4])
IndexError: list index out of range
A negative indexing counts from backwards.
>>> ls=[34, 'hi', [2,3],-5]
>>> print(ls[-1])
-5
>>> print(ls[-3])
hi
The in operator applied on lists will results in a Boolean value.
>>> ls=[34, 'hi', [2,3],-5]
>>> 34 in ls
True
>>> -2 in ls
False
Getting a List’s Length with len()
The len() function will return the number of values that are in a list value passed to it, just like it
can count the number of characters in a string value.
Example:
>>> spam = ['cat', 'dog', 'moose']
>>> len(spam)
3
List Operations
Two List Operations are: List Concatenation and List Replication
The + operator can combine two lists to create a new list value in the same way it combines two
strings into a new string value.
Whereas * operator take one list object and one integer value, say n, and returns a list by repeating
Mamatha A, Asst Prof, Dept of CSE, SVIT Page 5
Application Development Using Python (18CS55) Module II
>>> ls1=[1,2,3]
>>> print(ls1*3) #repetition using *
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Traversing a List
A list can be traversed using for loop.
If we need to use each element in the list, we can use the for loop and in operator as below
Example: To Print the elements of a list
>>> ls=[34, 'hi', [2,3],-5]
>>> for item in ls:
print(item)
OUTPUT:
34
hi
[2,3]
-5
List elements can be accessed with the combination of range() and len() functions as well –
Example:
ls=[1,2,3,4]
for i in range(len(ls)):
ls[i]=ls[i]**2
print(ls)
Mamatha A, Asst Prof, Dept of CSE, SVIT Page 6
Application Development Using Python (18CS55) Module II
#output is
[1, 4, 9, 16]
Here, we wanted to do modification in the elements of list. Hence, referring indices is suitable than
referring elements directly.
The len() returns total number of elements in the list (here it is 4).
Then range() function makes the loop to range from 0 to 3 (i.e. 4-1).
Then, for every index, we are updating the list elements (replacing original value by its square).
List Methods
A Python method is like a Python function, but it must be called on an object(value).
The method part comes after the value(object), separated by a period.
Syntax: object.method_name(<args>) #method call
Each data type has its own set of methods.
The list data type, for example, has several useful methods for finding, adding, removing, and
otherwise manipulating values in a list.
Some of the List Methods are:
Adding Values to Lists with the append() and insert() Methods
Finding a Value in a List with the index() Method
Sorting the Values in a List with the sort() Method
Reversing the Values in a List with the reverse method
Removing Values from Lists with pop()
append(): This method is used to add a new element at the end of a list.
>>> ls=[1,2,3]
>>> ls.append(„hi‟)
>>> ls.append(10)
>>> print(ls)
[1, 2, 3, „hi‟, 10]
extend(): This method takes a list as an argument and all the elements in this list are added at the
sort(): This method is used to sort the contents of the list. By default, the function will sort the
items in ascending order.
>>> ls=[3,10,5, 16,-2]
>>> ls.sort()
>>> print(ls)
[-2, 3, 5, 10, 16]
When we want a list to be sorted in descending order, we need to set the argument as shown
>>> ls.sort(reverse=True)
>>> print(ls)
[16, 10, 5, 3, -2]
count(): This method is used to count number of occurrences of a particular value within list.
>>> ls=[1,2,5,2,1,3,2,10]
>>> ls.count(2)
3 #the item 2 has appeared 3 times in ls
>>> ls.count(54) #the item 54 is not present in ls, hence it returns 0
0
clear(): This method removes all the elements in the list and makes the list empty.
>>> ls=[1,2,3]
>>> ls.clear()
>>> print(ls)
[]
index(): This method is used to get the index position of a particular value in the list.
>>> ls=[4, 2, 10, 5, 3, 2, 6]
>>> ls.index(2)
1
Here, the number 2 is found at the index position 1. Note that, this function will give index of
only the first occurrence of a specified value.
The same function can be used with two more arguments start and end to specify a range
within which the search should take place.
2. The sort() function can be applied only when the list contains elements of compatible types. But, if
a list is a mix non-compatible types like integers and string, the comparison cannot be done.
Hence, Python will throw TypeError.
For example,
>>> ls=[34, 'hi', -5]
>>> ls.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
Similarly, when a list contains integers and sub-list, it will be an error.
>>> ls=[34,[2,3],5]
>>> ls.sort()
TypeError: '<' not supported between instances of 'list' and 'int'
Integers and floats are compatible and relational operations can be performed on them. Hence,
we can sort a list containing such items.
>>> ls=[3, 4.5, 2]
>>> ls.sort()
>>> print(ls)
[2, 3, 4.5]
3. The sort() function uses one important argument keys.
4. Most of the list methods like append(), extend(), sort(), reverse() etc. modify the list object
internally and return None.
>>> ls=[2,3]
>>> ls1=ls.append(5)
>>> print(ls)
[2,3,5]
>>> print(ls1)
None
Deleting Elements
Elements can be deleted from a list in different ways. Python provides few built-in methods for
removing elements as given below –
pop(): This method deletes the last element in the list, by default.
>>> ls=[3,6,-2,8,10]
>>> x=ls.pop() #10 is removed from list and stored in x
>>> print(ls)
[3, 6, -2, 8]
>>> print(x)
10
When an element at a particular index position has to be deleted, then we can give that position as
argument to pop() function.
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1) #item at index 1 is popped
>>> print(t)
['a', 'c']
>>> print(x) b
remove(): When we don‟t know the index, but know the value to be removed, then this function
can be used.
>>> ls=[5,8, -12,34,2]
>>> ls.remove(34)
>>> print(ls)
[5, 8, -12, 2]
Note that, this function will remove only the first occurrence of the specified value, but not all
occurrences.
>>> ls=[5,8, -12, 34, 2, 6, 34]
>>> ls.remove(34)
>>> print(ls)
[5, 8, -12, 2, 6, 34]
Unlike pop() function, the remove() function will not return the value that has been deleted.
while (True):
x= input('Enter a number: ')
if x== 'done':
break
x= float(x)
ls.append(x)
average = sum(ls) / len(ls)
print('Average:', average)
2.2 TUPLE
>>> t2=tuple()
>>> type(t2)
<class 'tuple'>
If we provide an argument of type sequence (a list, a string or tuple) to the method tuple(), then a tuple with
the elements in a given sequence will be created:
>>> x,y=10,20
>>> print(x) #prints 10
>>> print(y) #prints 20
When we have list of items, they can be extracted and stored into multiple variables as below –
>>> ls=["hello", "world"]
>>> x,y=ls
>>> print(x) #prints hello
>>> print(y) #prints world
This code internally means that –
x= ls[0]
y= ls[1]
The best known example of assignment of tuples is swapping two values as below –
>>> a=10
>>> b=20
>>> a, b = b, a
>>> print(a, b) #prints 20 10
In the above example, the statement a, b = b, a is treated by Python as – LHS is a set of variables, and RHS
is set of expressions.
The expressions in RHS are evaluated and assigned to respective variables at LHS.
>>> email='[email protected]'
>>> usrName, domain = email.split('@')
>>> print(usrName) #prints mamathaa
>>> print(domain) #prints ieee.org
As dictionary may not display the contents in an order, we can use sort() on lists and then print in required
order as below –
>>> d = {'a':10, 'b':1, 'c':22}
>>> t = list(d.items())
>>> print(t)
[('b', 1), ('a', 10), ('c', 22)]
>>> t.sort()
>>> print(t)
[('a', 10), ('b', 1), ('c', 22)]
print("List of tuples:",ls)
ls.sort(reverse=True)
print("List of sorted tuples:",ls)
The output would be –
List of tuples: [(9291, 'Tom'), (3501, 'Jerry'), (8913, 'Donald')]
List of sorted tuples: [(9291, 'Tom'), (8913, 'Donald'), (3501, 'Jerry')]
In the above program, we are extracting key, val pair from the dictionary and appending it to the list ls.
While appending, we are putting inner parentheses to make sure that each pair is treated as a tuple.
Then, we are sorting the list in the descending order.
The sorting would happen based on the telephone number (val), but not on name (key), as first element in
tuple is telephone number (val).
Built In Functions
2.3 DICTIONARIES
A dictionary is a collection of unordered set of key:value pairs, with the requirement that keys are
unique in one dictionary.
Unlike lists and strings where elements are accessed using index values (which are integers), the
values in dictionary are accessed using keys.
A key in dictionary can be any immutable type like strings, numbers and tuples. (The tuple can be
made as a key for dictionary, only if that tuple consist of string/number/ sub-tuples).
As lists are mutable – that is, can be modified using index assignments, slicing, or using methods
like append(), extend() etc, they cannot be a key for dictionary.
One can think of a dictionary as a mapping between set of indices (which are actually keys) and a
set of values.
Each key maps to a value.
An empty dictionary can be created using two ways –
d= {}
OR
d=dict()
>>> tel_dir['Donald']=4793
>>> print(tel_dir)
{'Tom': 3491, 'Jerry': 8135, 'Donald': 4793}
NOTE that the order of elements in dictionary is unpredictable. That is, in the above example, don‟t
assume that 'Tom': 3491 is first item, 'Jerry': 8135 is second item etc. As dictionary members are not
indexed over integers, the order of elements inside it may vary. However, using a key, we can extract its
associated value as shown below –
>>> print(tel_dir['Jerry'])
8135
Here, the key 'Jerry' maps with the value 8135, hence it doesn‟t matter where exactly it is inside the
dictionary.
If a particular key is not there in the dictionary and if we try to access such key, then the KeyError is
generated.
>>> print(tel_dir['Mickey'])
KeyError: 'Mickey'
While indexing is used with other data types to access values, dictionary uses keys. Key can be used
either inside square brackets or with the get() method. The difference while using get() is that it
returns None instead of KeyError, if the key is not found
The len() function on dictionary object gives the number of key-value pairs in that object.
>>> print(tel_dir)
{'Tom': 3491, 'Jerry': 8135, 'Donald': 4793}
>>> len(tel_dir)
3
The in operator can be used to check whether any key (not value) appears in the dictionary object.
>>> 'Mickey' in tel_dir #output is False
>>> 'Jerry' in tel_dir #output is True
>>> 3491 in tel_dir #output is False
We observe from above example that the value 3491 is associated with the key 'Tom' in tel_dir. But,
the in operator returns False.
The dictionary object has a method values() which will return a list of all the values associated
with keys within a dictionary.
If we would like to check whether a particular value exist in a dictionary, we can make use of it as
shown below –
>>> 3491 in tel_dir.values() #output is True
The in operator behaves differently in case of lists and dictionaries as explained hereunder:
When in operator is used to search a value in a list, then linear search algorithm is used internally.
That is, each element in the list is checked one by one sequentially. This is considered to be
Modifying Dictionary
Dictionary are mutable. We can add new items or change the value of existing items using
assignment operator.
If the key is already present, value gets updated, else a new key: value pair is added to the
dictionary.
We can remove a particular item in a dictionary by using the method pop(). This method removes as
item with the provided key and returns the value.
All the items can be removed at once using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
The method, popitem() can be used to remove and return an arbitrary item (key, value) form the
dictionary.
Enter a string:
Hello World
{'H': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'W': 1, 'r': 1, 'd': 1}
It can be observed from the output that, a dictionary is created here with characters as keys and
frequencies as values. Note that, here we have computed histogram of counters.
Dictionary in Python has a method called as get(), which takes key and a default value as two
arguments. If key is found in the dictionary, then the get() function returns corresponding value,
otherwise it returns default value.
For example,
>>> tel_dir={'Tom': 3491, 'Jerry':8135, 'Mickey':1253}
>>> print(tel_dir.get('Jerry',0))
8135
>>> print(tel_dir.get('Donald',0))
0
In the above example, when the get() function is taking 'Jerry' as argument, it returned
corresponding value, as 'Jerry'is found in tel_dir.
Whereas, when get() is used with 'Donald' as key, the default value 0 (which is provided by us) is
returned.
The function get() can be used effectively for calculating frequency of alphabets in a string.
Here is the modified version of the program –
s=input("Enter a string:")
d=dict()
for ch in s:
d[ch]=d.get(ch,0)+1
print(d)
In the above program, for every character ch in a given string, we will try to retrieve a value. When
Output would be –
Tom 3491
Jerry 8135
Mickey 1253
Note that, while accessing items from dictionary, the keys may not be in order. If we want to print
the keys in alphabetical order, then we need to make a list of the keys, and then sort that list.
There are three dictionary methods that will return list-like values of the dictionary‟s keys, values,
or both keys and values: keys(), values(), and items().
The values returned by these methods are not true lists: They cannot be modified and do not have
an append() method.
If you want a true list from one of these methods, pass its list-like return value to the list()
function.
But these data types (dict_keys, dict_values, and dict_items, respectively) can be used in for
loops.
Using the keys(), values(), and items() methods, a for loop can iterate over the keys, values, or
key-value pairs in a dictionary, respectively.
We can do so using keys() method of dictionary and sort() method of lists.
Consider the following code –
Mamatha A, Asst Prof, Dept of CSE, SVIT Page 28
Application Development Using Python (18CS55) Module II
Note: The key-value pair from dictionary can be together accessed with the help of a method items()
as shown
We need to check whether a key exists in a dictionary before accessing that key‟s
value.
In dictionaries, we have a get() method that takes two arguments: the key and a
fallback value
If key is present it returns its value else it returns the default value if that key does not
exist.
If default value is not specified, the get() method will raise an error “Key Error” if
the key does not exist
We can set a value in a dictionary for a certain key only if that key does not already have a value.
The setdefault() method offers a way to do this in one line of code.
The first argument passed to the method is the key to check for, and the second argument is the
value to set at that key if the key does not exist.
If the key does exist, the setdefault() method returns the key‟s value.
Pretty Printing
The pprint() and pformat() functions available in module pprint will “pretty print” a
dictionary‟s values.
This is helpful when you want a cleaner display of the items in a dictionary than what
print() provides.
The pprint.pprint() function is especially helpful when the dictionary itself contains
nested lists or dictionaries.
If you want to obtain the prettified text as a string value instead of displaying it on the
screen, call pprint.pformat() instead.
Program is given below:
OUTPUT:
Inside the totalBrought() function, the for loop iterates over the key-value pairs in guests .
Inside the loop, the string of the guest‟s name is assigned to k, and the dictionary of picnic items
Mamatha A, Asst Prof, Dept of CSE, SVIT Page 33
Application Development Using Python (18CS55) Module II
character H e l l o w o r l d
index 0 1 2 3 4 5 6 7 8 9 10
The characters of a string can be accessed using index enclosed within square brackets.
So, H is the 0th letter, e is the 1th letter and l is the 2th letter of “Hello world”
For example,
>>> word1="Hello"
>>> word2='hi'
>>> x=word1[1] #2nd character of word1 is extracted
>>> print(x)
e
>>> y=word2[0] #1st character of word1 is extracted
>>> print(y)
h
Python supports negative indexing of string starting from the end of the string as shown below:
S= “Hello World”
character H e l l o w o r l d
Negative index -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
The characters can be extracted using negative index also, which count backward from the end of
the string.
For example:
Mamatha A, Asst Prof, Dept of CSE, SVIT Page 35
Application Development Using Python (18CS55) Module II
>>> var=“Hello”
>>> print(var[-1])
o
>>> print(var[-4])
e
Whenever the string is too big to remember last positive index, one can use negative index to
extract characters at the end of string.
st="Hello"
for i in st:
print(i, end='\t')
Output:
H e l l o
In the above example, the for loop is iterated from first to last character of the string st. That is, in
every iteration, the counter variable i takes the values as H, e, l, l and o. The loop terminates when
no character is left in st.
Using while loop:
st="Hello"
i=0
while i<len(st):
print(st[i], end=„\t‟)
i+=1
Output:
H e l l o
In this example, the variable i is initialized to 0 and it is iterated till the length of the string. In
every iteration, the value of i is incremented by 1 and the character in a string is extracted using i
as index.
Example: Write a while loop that starts at the last character in the string and traverses backwards
to the first character in the string, printing each letter on separate line
str="Hello"
i=-1
while i>=-len(str):
print(str[i])
i-=1
Output:
o
l
l
e
H
String Slices
A segment or a portion of a string is called as slice.
Only a required number of characters can be extracted from a string using colon (:) symbol.
The basic syntax for slicing a string would be – st[i:j:k]
This will extract character from ith character of st till (j-1)th character in steps of k.
If first index is not present, it means that slice should start from the beginning of the string. I
f the second index j is not mentioned, it indicates the slice should be till the end of the string.
The third parameter k, also known as stride, is used to indicate number of steps to be incremented
after extracting first character. The default value of stride is 1.
Consider following examples along with their outputs to understand string slicing.
st="Hello World" #refer this string for all examples
Starting from 7th index to till the end of string, characters will be printed.
8. print(st[3:8:2]) #output is l o
Starting from 3rd character, till 7th character, every alternative index is considered.
By the above set of examples, one can understand the power of string slicing and of Python script.
The slicing is a powerful tool of Python which makes many task simple pertaining to data types like
strings, Lists, Tuple, Dictionary etc. (Other types will be discussed in later Modules)
So, to achieve our requirement, we can create a new string using slices of existing string as below
def count(st,ch):
cnt=0
for i in st:
if i==ch:
cnt+=1
return cnt
st=input("Enter a string:")
ch=input("Enter a character to be counted:")
c=count(st,ch)
print("%s appeared %d times in %s"%(ch,c,st))
Output:
Enter a string: hello how are you?
Enter a character to be counted: h
h appeared 2 times in hello how are you?
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.
For example,
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.
Internally, such comparison happens using ASCII codes of respective characters.
Consider following examples –
Output is same. As the value contained in st and hello both are same, the equality results in True.
if st<= „Hello‟:
print(„lesser‟)
else:
print(„greater‟)
Output is greater. The ASCII value of h is greater than ASCII value of H. Hence, hello
is greater than Hello.
NOTE: A programmer must know ASCII values of some of the basic characters. Here are few –
A–Z : 65 – 90
a–z : 97 – 122
0–9 : 48 – 57
Space : 32
Enter Key : 13
String Methods
String is basically a class in Python.
When we create a string in program, an object of that class will be created.
A class is a collection of member variables and member methods (or functions).
When we create an object of a particular class, the object can use all the members (both variables
and methods) of that class.
Python provides a rich set of built-in classes for various purposes. Each class is enriched with a
useful set of utility functions and variables that can be used by a Programmer.
A programmer can create a class based on his/her requirement, which are known as user-defined
classes.
The built-in set of members of any class can be accessed using the dot operator as shown–
objName.memberMethod(arguments)
The dot operator always binds the member name with the respective object name. This is very
essential because, there is a chance that more than one class has members with same name. To
avoid that conflict, almost all Object oriented languages have been designed with this common
[' add ', ' class ', ' contains ', ' delattr ', ' dir ', ' doc ', ' eq ', ' format ', ' ge ', ' getattribute ',
' getitem ', ' getnewargs ', ' gt ', ' hash ', ' init ', ' init_subclass ', ' iter ', ' le ', ' len ', ' lt ',
' mod ', ' mul ', ' ne ', ' new ', ' reduce ', ' reduce_ex ', ' repr ', ' rmod ', ' rmul ', ' setattr
', ' sizeof ', ' str ', ' subclasshook ', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith',
'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind',
'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']
Note that, the above set of variables and methods are common for any object of string class that
we create.
Each built-in method has a predefined set of arguments and return type.
To know the usage, working and behavior of any built-in method, one can use the command help.
For example, if we would like to know what is the purpose of islower() function (refer above list
to check its existence!!), how it behaves etc, we can use the statement –
>>> help(str.islower)
Help on method_descriptor:
islower(...)
S.islower() -> bool
Return True if all cased characters in S are lowercase and if there is at least one upper cased character
Observe in Ex2 that the first character is converted to uppercase, and an in-between uppercase
letter W of the original string is converted to lowercase.
s.upper(): This function returns a copy of a string s to uppercase. As strings are immutable, the
original string s will remain same.
>>> st='HELLO'
>>> st1=st.lower()
>>> print(st1) hello
>>> print(st) #no change in original string
HELLO
s.find(s1) : The find() function is used to search for a substring s1 in the string s. If found, the
index position of first occurrence of s1 in s, is returned. If s1 is not found in s, then -1 is returned.
>>> st='hello'
>>> i=st.find('l')
>>> print(i) #output is 2
>>> i=st.find('lo')
>>> print(i) #output is 3
>>> print(st.find(„x‟)) #output is -1
The find() function can take one more form with two additional arguments viz. start and end
positions for search.
>>> st="calender of Feb. cal of march"
>>> i= st.find(„cal‟)
>>> print(i) #output is 0
Here, the substring „cal‟is found in the very first position of st, hence the result is 0.
>>> i=st.find('cal',10,20)
>>> print(i) #output is 17
Here, the substring cal is searched in the string st between 10th and 20th position and hence the
result is 17.
>>> i=st.find('cal',10,15)
>>> print(i) #output is -1
In this example, the substring 'cal' has not appeared between 10th and 15th character of st.
Hence, the result is -1.
s.strip(): Returns a copy of string s by removing leading and trailing white spaces.
S.startswith(prefix, start, end): This function has 3 arguments of which start and end are
option. This function returns True if S starts with the specified prefix, False otherwise.
>>> st="hello world"
>>> st.startswith("he") #returns True
When start argument is provided, the search begins from that position and returns True or False
based on search result.
>>> st="hello world"
The startswith() function requires case of the alphabet to match. So, when we are not sure about
the case of the argument, we can convert it to either upper case or lowercase and then use
startswith()function as below –
>>> st="Hello"
>>> st.startswith("he") #returns False
>>> st.lower().startswith("he") #returns True
S.count(s1, start, end): The count() function takes three arguments – string, starting position
and ending position. This function returns the number of non-overlapping occurrences of
substring s1 in string S in the range of start and end.
>>> st="hello how are you? how about you?"
>>> st.count('h') #output is 3
>>> st.count(„how‟) #output is 2
>>> st.count(„how‟,3,10) #output is 1 because of range given
Example:
st=input("Enter a string:")
ch=input("Enter a character to be counted:")
c=st.count(ch)
print("%s appeared %d times in %s"%(ch,c,st))
Working with Strings
Typing string values in Python code is fairly straightforward: They begin and end with a single
quote.
But then how can you use a quote inside a string?
Typing 'That is Alice's cat.' won‟t work, because Python thinks the string ends after Alice, and the
rest (s cat.') is invalid Python code.
Fortunately, there are multiple ways to type strings.
Double Quotes
Escape Characters
Raw Strings
Double Quotes
Strings can begin and end with double quotes, just as they do with single quotes.
One benefit of using double quotes is that the string can have a single quote character in it,
because double quote is treated as the start and end of the string
Escape Characters
An escape character lets the programmer to use characters that are otherwise impossible to put
into a string.
An escape character consists of a backslash (\) followed by the character want to be added to
the string. (Despite consisting of two characters, it is commonly referred to as a singular escape
character.)
For example, the escape character for a single quote is \'.
We can use this inside a string that begins and ends with single quotes.
Raw Strings
We can place an r before the beginning quotation mark of a string to make it a raw string.
A raw string completely ignores all escape characters and prints any backslash that appears in
the string.
In raw string, Python considers the backslash as part of the string and not as the start of an
escape character.
Multiline Strings
While we can use the \n escape character to put a newline into a string, it is often easier to use
multiline strings.
A multiline string in Python begins and ends with either three single quotes or three double
quotes.
Any quotes, tabs, or newlines in between the “triple quotes” are considered part of the string..
MultiLine Comments
While the hash character (#) marks the beginning of a comment for the rest of the line
A multiline string is often used for comments that span multiple lines.
OUTPUT:
Parsing Strings
Sometimes, we may want to search for a substring matching certain criteria.
For example, finding domain names from email-Ids in the list of messages is a useful task in some
projects.
Consider a string below and we are interested in extracting only the domain name.
print(host)
Output:
Position of @ is 14
Position of space after @ is 29
saividya.ac.in
Format Operator
The format operator, % allows us to construct strings, replacing parts of the strings with the data
stored in variables.
The first operand is the format string, which contains one or more format sequences that specify
how the second operand is formatted.
Syntax: “<format>” % (<values>)
The result is a string.
>>> sum=20
>>> '%d' %sum
„20‟ #string ‘20’, but not integer 20
Note that, when applied on both integer operands, the % symbol acts as a modulus operator.
When the first operand is a string, then it is a format operator.
Consider few examples illustrating usage of format operator.
In [2]: type(ls)
Out[2]: list
In [4]: print(ls1)
In [5]: ls2=["ISE","CSE"]
ls3=ls1+ls2 # List Concatenation
print(ls3)
In [7]: len(ls2)
Out[7]: 6
In [8]: ls2[4]
Out[8]: 'ISE'
In [9]: ls2[-4]
Out[9]: 'ISE'
In [10]: ls=[1,2,3]
ls.append("hi")
ls.append(34)
print(ls)
None
In [12]: ls.append("heelo",45.6)
------------------------------------------------------------------------
TypeError Traceback (most recent call la
<ipython-input-12-1467a604d71d> in <module>
----> 1 ls.append("heelo",45.6)
In [14]: ls=[3,4.5,"world"]
ls.insert(2,"hi") # Insert at index 2 after 4.5
print(ls)
In [15]: ls.insert(-1,'is')
print(ls)
In [16]: ls.insert(-2,34)
print(ls)
In [17]: spam=['a','b','c','d']
print(spam[int('3'*2)/11])
------------------------------------------------------------------------
TypeError Traceback (most recent call la
<ipython-input-17-3859695216c7> in <module>
1 spam=['a','b','c','d']
----> 2 print(spam[int('3'*2)/11])
In [18]: '3'*2
Out[18]: '33'
In [19]: int('33')
Out[19]: 33
In [20]: 33/11
Out[20]: 3.0
In [21]: spam[3.0]
------------------------------------------------------------------------
TypeError Traceback (most recent call la
<ipython-input-21-a7afae461759> in <module>
----> 1 spam[3.0]
In [ ]:
In [1]: ls=[2,7,4,2,7,8,5] #Creating a List
ls.index(2) #Index of a particular element in a list # Answer is 0
ls.index(10) #Answer is ValueError
ls.index(7,2,5) #7 is element, 2 and 5 denotes the range, search in the
------------------------------------------------------------------------
ValueError Traceback (most recent call la
<ipython-input-1-c64ecd035280> in <module>
1 ls=[2,7,4,2,7,8,5] #Creating a List
2 ls.index(2) #Index of a particular element in a list # Answer is
----> 3 ls.index(10) #Answer is ValueError
4 ls.index(7,2,5) #7 is element, 2 and 5 denotes the range, search
list from index 2 to 4
In [2]: ls.index(2)
Out[2]: 0
In [3]: ls.index(7,2,5)
Out[3]: 4
In [4]: ls.index(7,2,4)
------------------------------------------------------------------------
ValueError Traceback (most recent call la
<ipython-input-4-63326d6aa562> in <module>
----> 1 ls.index(7,2,4)
In [5]: ls=[2,3,10,1,-9,-2]
ls.sort()
print(ls)
------------------------------------------------------------------------
TypeError Traceback (most recent call la
<ipython-input-6-62872549b00e> in <module>
1 ls=[2,3,"hello",34.0]
----> 2 ls.sort()
In [7]: ls=[2,3,10,1,-9,-2]
ls.sort(reverse=True)
In [8]: print(ls)
In [9]: ls=['a','z','A','B']
ls.sort() #ASCIIbetical Order
print(ls)
In [11]: print(ls)
In [12]: ls=[2,3,4,5,6,7,2,6,2]
ls.count(2)
Out[12]: 3
In [13]: ls.count(53)
Out[13]: 0
In [14]: ls=[2,3,4,8,-2,10]
x=ls.pop()
In [15]: print(ls)
print(x)
[2, 3, 4, 8, -2]
10
In [16]: x=pop(3)
print(ls)
print(x)
------------------------------------------------------------------------
NameError Traceback (most recent call la
<ipython-input-16-c792f1fcb159> in <module>
----> 1 x=pop(3)
2 print(ls)
3 print(x)
In [17]: x=ls.pop(3)
print(ls)
print(x)
[2, 3, 4, -2]
8
In [18]: x=ls.pop(4)
------------------------------------------------------------------------
IndexError Traceback (most recent call la
<ipython-input-18-ca96ac0c134f> in <module>
----> 1 x=ls.pop(4)
In [21]: ls=[2,3,4,6,12,-1,34]
len(ls) # length = 7
max(ls) # max=34
min(ls) # min=-1
sum(ls) #sum= 60
Out[21]: 60
In [22]: len(ls)
Out[22]: 7
In [23]: max(ls)
Out[23]: 34
In [24]: min(ls)
Out[24]: -1
In [ ]:
In [1]: # -7 ,-6 ,-5 ,-4 , -3, -2, -1 -ve indexing
ls=['a','b','c','d','e','f','g']
# 0 , 1 , 2 , 3 , 4 , 5 , 6 +ve indexing
In [8]: print(ls[1:-2])
In [9]: print(ls[2:-1:2])
['c', 'e']
In [10]: print(ls[-2:-6:-1])
In [12]: print(ls[2::2])
[]
In [14]: print(ls[::-1])
In [15]: print(ls[1:])
In [16]: ls[1:3]=['p','q']
print(ls)
In [18]: print(ls)
In [20]: ls[:]=['v','s','e','m']
print(ls)
In [21]: print(ls[:6])
In [22]: print(ls[4:6])
[]
In [ ]:
In [1]: t1=(10,20,"ADP",[12,23])
print(t1) # prints the tuple
ADP
20
In [4]: t1=(10,20.6,"Hello",[2,3,5])
t1[0]=23 #Error
--------------------------------------------------------------------------
TypeError Traceback (most recent call last
<ipython-input-4-e6f44c5e0275> in <module>
1 t1=(10,20.6,"Hello",[2,3,5])
----> 2 t1[0]=23 #Error
--------------------------------------------------------------------------
TypeError Traceback (most recent call last
<ipython-input-5-98481bd725de> in <module>
----> 1 t1[3]="heelo" #Error
In [6]: t1=(10,20.6,"Hello",[2,3,5])
t1[3][2]=23 # [2,3,5] will become [2,3,23]
In [7]: print(t1)
--------------------------------------------------------------------------
TypeError Traceback (most recent call last
<ipython-input-8-37dc73fe8d89> in <module>
----> 1 t1[2][1]="E"
In [9]: t1=(10,20,30.5,"ADP")
t2=t1 # assignment
print(id(t1))
print(id(t2))
2095139374328
2095139374328
() ()
In [12]: t3=tuple([12,23,45])
print(t3) # tuple contaning the elements of the list
In [13]: t4=tuple((23,34,45))
print(t4) #tuple containing the elements of the tuple
In [14]: t4=tuple(([2,3],[4,5]))
print(t4)
In [15]: t4=tuple(([2,3],[4,5],"ADP"))
print(t4)
Out[16]: 3
In [17]: t1=(12,23,34)
t2=([12,3],"ADP")
#Concatenation of tuples using '+' operator
t3=t1+t2
print(t3)
#Replication Operation
t4=t1*2
print(t4)
In [18]: t=("Mango","Pineapple","Orange")
t1=("Kiwi",)+t[1:] #slicing operator for tuples
print(t)
print(t1)
In [19]: t=("Mango","Pineapple","Orange")
t1=("Kiwi")+t[1:] #slicing operator for tuples
print(t)
print(t1)
--------------------------------------------------------------------------
TypeError Traceback (most recent call last
<ipython-input-19-8c39d09c714b> in <module>
1 t=("Mango","Pineapple","Orange")
----> 2 t1=("Kiwi")+t[1:] #slicing operator for tuples
3 print(t)
4 print(t1)
In [20]: t=(1,2,3)
del t[2] # Error
--------------------------------------------------------------------------
TypeError Traceback (most recent call last
<ipython-input-20-c50a5bd2c18f> in <module>
1 t=(1,2,3)
----> 2 del t[2] # Error
(1, 2, 3)
--------------------------------------------------------------------------
NameError Traceback (most recent call last
<ipython-input-21-9140215c0778> in <module>
1 print(t)
2 del t
----> 3 print(t)
In [ ]:
Working of Dictionaries
In [1]: #Creating empty dictionary
d={}
print(type(d)) # d is an instance of class dict
<class 'dict'>
<class 'dict'>
Out[4]: 2
5678
------------------------------------------------------------------------
KeyError Traceback (most recent call la
<ipython-input-7-954eb3203613> in <module>
----> 1 print(d["Donald"]) # Error
KeyError: 'Donald'
In [8]: d.get("Tom")
Out[8]: 2345
None
In [11]: print(d)
In [13]: print(d)
In [15]: print(d)
In [17]: print(d)
print(res)
In [18]: res=d.pop("Mickey")
------------------------------------------------------------------------
KeyError Traceback (most recent call la
<ipython-input-18-8b2a03f23ba0> in <module>
----> 1 res=d.pop("Mickey")
KeyError: 'Mickey'
{'Donald': 3456}
In [21]: d["Tom"]=3456
d["Jerry"]=56768
In [22]: print(d)
res=d.popitem() #popitem removes random element in the dictionary
print(d)
In [24]: print(d)
{}
------------------------------------------------------------------------
NameError Traceback (most recent call la
<ipython-input-25-b2ca46cae230> in <module>
1 d={'Donald': 3456, 'Tom': 3456, 'Jerry': 56768}
2 del d
----> 3 print(d) #NameError
In [ ]:
Working of Dictionaries
In [1]: tel_dir={"tom":2345,"jerry":4567,"mickey":3489}
for name in tel_dir:
print(name) #print the keys in the dictionary
tom
jerry
mickey
In [2]: tel_dir={"tom":2345,"jerry":4567,"mickey":3489}
for name in tel_dir:
print(name,":",tel_dir[name]) #print the key/value in the diction
tom : 2345
jerry : 4567
mickey : 3489
Out[3]: True
Out[4]: False
Out[5]: True
In [12]: print(tel_dir)
In [13]: birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'} # init
while True:
print('Enter a name: (blank to quit)')
name = input()
if name == ' ':
break
if name in birthdays: #checks whether name is already in dictio
print(birthdays[name] , ' is the birthday of ' , name)
else:
print('I do not have birthday information for ' , name)
print('What is their birthday?')
bday = input()
birthdays[name] = bday #add the information to the dictionary
print('Birthday database updated.')
print(birthdays)
In [ ]:
Working with dictionary methods ¶
In [1]: d={"Tom":3456,"Jerry":464467,"Mickey":5657}
print(d.get("Jery",0)) #default value is useful, when key doesn't exist
In [2]: d={"Tom":3456,"Jerry":464467,"Mickey":5657}
print(d.get("Jerry",0)) #default value is useful, when key doesn't exis
464467
In [3]: d={"Tom":3456,"Jerry":464467,"Mickey":5657}
print(d.pop("Jery")) #default value is useful, when key doesn't exists
------------------------------------------------------------------------
KeyError Traceback (most recent call la
<ipython-input-3-b854deea3c48> in <module>
1 d={"Tom":3456,"Jerry":464467,"Mickey":5657}
----> 2 print(d.pop("Jery")) #default value is useful, when key doesn't
KeyError: 'Jery'
In [4]: d={"Tom":3456,"Jerry":464467,"Mickey":5657}
print(d.pop("Jery",0)) #default value is useful, when key doesn't exist
In [5]: d={"Tom":3456,"Jerry":464467,"Mickey":5657}
print(d.pop("Jerry",0)) #default value is useful, when key doesn't exis
464467
In [6]: print(d)
------------------------------------------------------------------------
NameError Traceback (most recent call la
<ipython-input-7-2e6b9e7b5aa0> in <module>
4 value=25 #default value
5 fruits=dict.fromkeys(ls,value) #first arg is keys and second a
alue for every key
----> 6 print(fruit)
In [9]: d1=dict.fromkeys(d,25)
print(d)
print(d1)
s
a
i
v
i
d
y
a
d={"One":1,"Two":2}
d1={"Two":"two"}
d.update(d1) #update()
print(d)
d={"One":1,"Two":2}
d1={"Two":"two","Three":3}
d.update(d1) #update()
print(d)
3064060873688
3064061178168
d.popitem()
Out[16]: ('Three', 3)
In [ ]:
# Strings Introduction
In [1]: Str="Python"
print(type(Str)) #prints <class 'str'>
print(len(Str)) #prints 6
print(Str[4]) # o
print(Str[-1]) # n
Str[2]='t' #Type Error
<class 'str'>
6
o
n
------------------------------------------------------------------------
TypeError Traceback (most recent call la
<ipython-input-1-856d73056573> in <module>
4 print(Str[4]) # o
5 print(Str[-1]) # n
----> 6 Str[2]='t' #Type Error
In [2]: Str="Python"
str1=Str[:len(Str)-1]+'N'
print(str1)
PythoN
PythonPythonPython
P
y
t
h
o
n
Out[5]: True
In [6]: "eo" in "Hello" #in operator - False
Out[6]: False
In [8]: word="python"
reverse=word[::-1]
if word == reverse:
print("Palindrome")
In [9]: word="python"
reverse=word[::-1]
if word == reverse:
print("Palindrome")
In [11]: word="python"
reverse=word[::-1]
print(reverse)
if word == reverse:
print("Palindrome")
nohtyp
In [12]: word="python"
reverse=word[::-1]
print(reverse)
if word == reverse:
print("Palindrome")
else:
print("Not a Palindrome")
nohtyp
Not a Palindrome
word="python programming"
vcount=0
vowels="aeiou"
for ch in word:
if ch in vowels:
vcount+=1
print("Number of vowels:",vcount)
Number of vowels: 4
In [14]: #To count number of vowels in a given string
word="python programming"
vcount=0
vowels="aeiou"
for ch in word:
if ch=='a' or ch=='o' or ch=='i':
vcount+=1
print("Number of vowels:",vcount)
Number of vowels: 4
In [ ]:
Working of String methods in Python
In [ ]: #Create a string
st="python Programming"
Syntax: strobject.MethodName(args)
In [ ]: #use of lower()
st="python Programming"
s1=st.lower() #returns a new string in lowercase
print(s1)
In [ ]: #use of upper()
st="python Programming"
s1=st.upper() #returns a new string in uppercase
print(s1)
In [ ]: #use of swapcase()
st="python Programming"
s1=st.swapcase() #returns a new string in changing the case
print(s1)
In [ ]: #use of title()
st="python programming"
s1=st.title() #returns a new string in title case format
print(s1)
In [ ]: #use of count()
st="python programming"
ct=st.count('n',0,6) #returns an integer value representing the number
print(ct)
In [ ]: #use of startswith()
st="python programming"
flag=st.startswith('program',7,20) #returns True or False
print(flag)
In [ ]: #use of endswith()
st="python programming"
flag=st.endswith('on') #returns True or False
print(flag)
In [ ]: #use of find()
st="python programming"
pos=st.find('p',7,13) #returns the position of first occurrence of sub
print(pos) #else -1 if not found
In [ ]: #use of index()
st="python programming"
pos=st.index('prog') #returns the position of first occurrence of subs
print(pos) #else raise an exception "Value Error" if not fo
In [ ]: #use of replace()
st="python programming"
s=st.replace('ming','s',1) #returns a new string by replacing old with
print(s) #python programs
print(st)
In [ ]: #use of center()
st="python programming"
st.center(12,'*') #returns a padded version of the string with spaces
In [ ]: #use of ljust/rjust()
st="python programming"
st.rjust(12,'$') #returns a padded version of the string with spaces in
In [ ]: #use of isupper()
st="Python programming"
st.upper().isupper() #returns True if all characters are in uppercase
In [ ]: #use of isalpha()
st="Python@programming"
st.isalpha() #returns True if all characters are alphabets else False
In [ ]: #use of isdigit()
st="123abc"
st.isdigit() #returns True if all characters are digits else False
In [ ]: #use of isalnum()
st="123ABC@"
st.isalnum() #returns True if all characters are either alphabets or d
In [ ]: #use of isspace()
st=" \t\n"
st.isspace() #returns True if all characters are spaces else False
In [ ]: #use of istitle()
st="Python Program"
st.istitle() #returns True if the string is in title case else False
In [ ]:
In [ ]: #usage of split()
s='python,programming'
ls=s.split(',') #return a list of words splitted based on deleimiter (sp
print(ls)
MultiLine Strings
In [29]: #Create a string that contains multiple lines using escape character
name="python \n vsem \n svit"
print(name)
python
vsem
svit
In [32]: #Create a string that contains multiple lines using multiline strings
name='''python's programming \t cse ise
v sem
svit'''
print(name)
MultiLine Comments
In [33]: '''This is a test Python program.
Written by Al Sweigart [email protected]
This program was designed for Python 3, not Python 2.
'''
def spam():
"""This is a multiline comment to help
explain what the spam() function does."""
print('Hello!')
spam()
Hello!
In [ ]: