Unit Iv
Unit Iv
PYTHON - STRINGS
Strings are amongst the most popular types in Python. We can create them simply by enclosing
characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as
simple as assigning a value to a variable. For example −
Python does not support a character type; these are treated as strings of length one, thus also considered
a substring.
To access substrings, use the square brackets for slicing along with the index or indices to obtain your
substring. For example −
var1[0]: H
var2[1:5]: ytho
Updating Strings
You can "update" an existing string by (re)assigning a variable to another string. The new value can
be related to its previous value or to a completely different string altogether. For example −
Escape Characters
Following table is a list of escape or non-printable characters that can be represented with backslash
notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\s 0x20 Space
\t 0x09 Tab
\x Character x
Assume string variable a holds 'Hello' and variable b holds 'Python', then −
[] Slice - Gives the character from the given index a[1] will give e
[:] Range Slice - Gives the characters from the given a[1:4] will give ell
range
not in Membership - Returns true if a character does not M not in a will give 1
exist in the given string
r/R Raw String - Suppresses actual meaning of Escape print r'\n' prints \n and print
characters. The syntax for raw strings is exactly the R'\n'prints \n
same as for normal strings with the exception of the
raw string operator, the letter "r," which precedes
the quotation marks. The "r" can be lowercase (r) or
uppercase (R) and must be placed immediately
preceding the first quote mark.
One of Python's coolest features is the string format operator %. This operator is unique to strings and
makes up for the pack of having functions from C's printf() family. Following is a simple example −
Here is the list of complete set of symbols which can be used along with % −
%c character
%o octal integer
Other supported symbols and functionality are listed in the following table −
Symbol Functionality
- left justification
# add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X',
depending on whether 'x' or 'X' were used.
m.n. m is the minimum total width and n is the number of digits to display
after the decimal point (if appl.)
Triple Quotes
Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including
verbatim NEWLINEs, TABs, and any other special characters.
The syntax for triple quotes consists of three consecutive single or double quotes.
When the above code is executed, it produces the following result. Note how every single special
character has been converted to its printed form, right down to the last NEWLINE at the end of the
string between the "up." and closing triple quotes. Also note that NEWLINEs occur either with an
explicit carriage return at the end of a line or its escape code (\n) −
Raw strings do not treat the backslash as a special character at all. Every character you put into a raw
string stays the way you wrote it −
print 'C:\\nowhere'
C:\nowhere
Now let's make use of raw string. We would put expression in r'expression' as follows −
print r'C:\\nowhere'
C:\\nowhere
STRING OPERATIONS IN PYTHON
Strings are sequences of characters. There are numerous algorithms for processing strings, including
for searching, sorting, comparing and transforming. Python strings are "immutable" which means they
cannot be changed after they are created. To create a string, put the sequence of characters inside either
single quotes, double quotes, or triple quotes and then assign it to a variable.
str = 'Hellow World!'
str = "Hellow World!"
str = """Sunday
Monday
Tuesday"""
6
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
String Concatenation
Joining of two or more strings into a single one is called concatenation. Python uses "+" operator for
joining one or more strings
str1 = 'Hellow '
str2 = ' World!'
print(str1 + str2)
output
Hellow World!
Reverse a String
In Python Strings are sliceable. Slicing a string gives you a new string from one point in the string,
backwards or forwards, to another point, by given increments. They take slice notation or a slice object
in a subscript:
string[subscript]
The subscript creates a slice by including a colon within the braces:
string[begin:end:step]
It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1, it reverses
a string.
7
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
STRING METHODS
Python has several built-in methods associated with the string data type. These methods let us easily
modify and manipulate strings. Built-in methods are those that are defined in the Python programming
language and are readily available for us to use. Here are some of the most common string methods.
output
7
output
PYTHON IS OBJECT ORIENTED
output
True
False
Python String endswith() method
String endswith() method returns Boolean TRUE, if the string Ends with the specified substring
otherwise, it will return False.
9
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
Oriented
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
output
Python is Object Oriented
PYTHON LIST
Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList
in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python. A
single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and
hence, they can be altered even after their creation.
List in Python are ordered and have a definite count. The elements in a list are indexed according to
a definite sequence and the indexing of a list is done with 0 being the first index. Each element in the
list has its definite place in the list, which allows duplicating of elements in the list, with each element
having its own distinct place and credibility.
In Python, a list is created by placing elements inside square brackets [], separated by commas.
# list of integers
my_list = [1, 2, 3]
A list can have any number of items and they may be of different types (integer, float, string, etc.).
# empty list
my_list = []
# list with mixed data types
my_list = [1, "Hello", 3.4]
12
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
A list can also have another list as an item. This is called a nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
There are various ways in which we can access the elements of a list.
List Index
We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a list having
5 elements will have an index from 0 to 4.
Trying to access indexes other than these will raise an IndexError. The index must be an integer. We
can't use float or other types, this will result in TypeError.
Nested lists are accessed using nested indexing.
Output
p
o
e
a
5
Traceback (most recent call last):
File "<string>", line 21, in <module>
TypeError: list indices must be integers or slices, not float
Lists are the most versatile data structures in Python since they are mutable, and their values can be
updated by using the slice and assignment operator.Python also provides append() and insert() methods,
which can be used to add values to the list.
Consider the following example to update the values inside the list.
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to the second index
list[2] = 10
print(list)
# Adding multiple-element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
14
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
The list elements can also be deleted by using the del keyword. Python also provides us
the remove() method if we do not know which element is to be deleted from the list.
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to second index
list[2] = 10
print(list)
# Adding multiple element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
The concatenation (+) and repetition (*) operators work in the same way as they were working with the
strings.Let's see how the list responds to various operators.
Membership It returns true if a particular item exists in a print(2 in l1) prints True.
particular list otherwise false.
Iteration The for loop is used to iterate over the list for i in l1:
elements. print(i)
Output
1
2
3
4
Python Tuple
Python Tuple is used to store the sequence of immutable Python objects. The tuple is similar to lists
since the value of the items stored in the list can be changed, whereas the tuple is immutable, and the
value of the items stored in the tuple cannot be changed.
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated by commas. The
parentheses are optional, however, it is a good practice to use them.A tuple can have any number of
items and they may be of different types (integer, float, list, string, etc.).
# Empty tuple
my_tuple = ()
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
Output
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
SN Function Description
1 cmp(tuple1, It compares two tuples and returns true if tuple1 is greater than
tuple2) tuple2 otherwise false.
PYTHON DICTIONARY
Python Dictionary is used to store the data in a key-value pair format. The dictionary is the data type
in Python, which can simulate the real-life data arrangement where some specific value exists for some
particular key. It is the mutable data-structure. The dictionary is defined into element Keys and values.
In other words, we can say that a dictionary is the collection of key-value pairs where the value can be
any Python object. In contrast, the keys are the immutable Python object, i.e., Numbers, string, or tuple.
The dictionary can be created by using multiple key-value pairs enclosed with the curly brackets {},
and each key is separated from its value by the colon (:).The syntax to define the dictionary is given
below.
Syntax:
In the above dictionary Dict, The keys Name and Age are the string that is an immutable object.
Output
<class 'dict'>
Printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
18
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
Python provides the built-in function dict() method which is also used to create dictionary. The empty
curly braces {} is used to create empty dictionary.
Output:
Empty Dictionary:
{}
We have discussed how the data can be accessed in the list and tuple by using the indexing. However,
the values can be accessed in the dictionary by using the keys as keys are unique in the dictionary. The
dictionary values can be accessed in the following way.
19
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
Output:
<class 'dict'>
printing Employee data ....
Name : John
Age : 29
Salary : 25000
Company : GOOGLE
Python provides us with an alternative to use the get() method to access the dictionary values. It would
give the same result as given by the indexing.
The dictionary is a mutable data type, and its values can be updated by using the specific keys. The
value can be updated along with key Dict[key] = value. The update() method is also used to update an
existing value. Note: If the key-value already present in the dictionary, the value gets updated.
Otherwise, the new keys added in the dictionary.
Example - 1:
Dict[2] = 'Joseph'
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
Dict[3] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# with a single Key
# The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[3] = 'JavaTpoint'
print("\nUpdated key value: ")
print(Dict)
Output:
Empty Dictionary:
{}
Example - 2:
Output:
Empty Dictionary:
{}
The items of the dictionary can be deleted by using the del keyword as given below.
print(Employee)
Output:
<class 'dict'>
printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
Deleting some of the employee data
printing the modified information
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined
The last print statement in the above code, it raised an error because we tried to print the Employee
dictionary that already deleted.
The pop() method accepts the key as an argument and remove the associated value. Consider the
following example.
# Creating a Dictionary
Dict = {1: 'JavaTpoint', 2: 'Peter', 3: 'Thomas'}
# Deleting a key
# using pop() method
pop_ele = Dict.pop(3)
print(Dict)
Output:
Python also provides a built-in methods popitem() and clear() method for remove elements from the
dictionary. The popitem() removes the arbitrary element from a dictionary, whereas the clear() method
removes all elements to the whole dictionary.
23
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
The built-in python dictionary methods along with the description are given below.
SN Function Description
1 cmp(dict1, It compares the items of both the dictionary and returns true if the first
dict2) dictionary values are greater than the second dictionary, otherwise it returns
false.
The built-in python dictionary methods along with the description are given below.
SN Method Description
3 dict.fromkeys(iterable, value = Create a new dictionary from the iterable with the values
None, /) equal to value.
4 dict.get(key, default = "None") It is used to get the value specified for the passed key.
8 dict.setdefault(key,default= It is used to set the key to the default value if the key is not
"None") specified in the dictionary
PYTHON SET
A Python set is the collection of the unordered items. Each element in the set must be unique,
immutable, and the sets remove the duplicate elements. Sets are mutable which means we can modify
it after its creation. Unlike other collections in Python, there is no index attached to the elements of the
set, i.e., we cannot directly access any element of the set by the index. However, we can print them all
together, or we can get the list of elements by looping through the set.
Creating a set
The set can be created by enclosing the comma-separated immutable items with the curly braces {}.
Python also provides the set() method, which can be used to create the set by the passed sequence.
Output:
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
Output:
It can contain any type of element such as integer, float, tuple etc. But mutable elements (list, dictionary,
set) can't be a member of set. Consider the following example.
print(type(set1))
#Creating a set which have mutable element
set2 = {1,2,3,["Javatpoint",4]}
print(type(set2))
Output:
<class 'set'>
In the above code, we have created two sets, the set set1 have immutable elements and set2 have one
mutable element as a list. While checking the type of set2, it raised an error, which means set can
contain only immutable elements.
Creating an empty set is a bit different because empty curly {} braces are also used to create a dictionary
as well. So Python provides the set() method used without an argument to create an empty set.
Output:
27
<class 'dict'>
<class 'set'>
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
Let's see what happened if we provide the duplicate element to the set.
set5 = {1,2,4,4,5,8,9,9,10}
print("Return set with unique elements:",set5)
Output:
In the above code, we can see that set5 consisted of multiple duplicate elements when we printed it
remove the duplicity from the set.
Python provides the add() method and update() method which can be used to add some particular item
to the set. The add() method is used to add a single element whereas the update() method is used to add
multiple elements to the set. Consider the following example.
Output:
To add more than one item in the set, Python provides the update() method. It accepts iterable as an
argument.
Output:
{'January', 'February', 'April', 'August', 'October', 'May', 'June', 'July', 'September', 'March'}
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
Python provides the discard() method and remove() method which can be used to remove the items
from the set. The difference between these function, using discard() function if the item does not exist
in the set then the set remain unchanged whereas remove() method will through an error.
Output:
June
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
Python provides also the remove() method to remove the item from the set. Consider the following
example to remove the items using remove() method.
Output:
We can also use the pop() method to remove the item. Generally, the pop() method will always remove
the last item but the set is unordered, we can't determine which element will be popped from set.
Consider the following example to remove the item from the set using pop() method.
print(Months)
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
Output:
In the above code, the last element of the Month set is March but the pop() method removed the June
and January because the set is unordered and the pop() method could not determine the last element
of the set.
Python provides the clear() method to remove all the items from the set.
Output:
Set can be performed mathematical operation such as union, intersection, difference, and symmetric
difference. Python provides the facility to carry out these operations with operators or methods. We
describe these operations as follows.
The union of two sets is calculated by using the pipe (|) operator. The union of the two sets contains all
the items that are present in both the sets.
Output:
Python also provides the union() method which can also be used to calculate the union of two sets.
Consider the following example.
Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
Days2 = {"Friday","Saturday","Sunday"}
print(Days1.union(Days2)) #printing the union of the sets
Output:
The intersection of two sets can be performed by the and & operator or the intersection() function.
The intersection of the two sets is given as the set of the elements that common in both sets.
Output:
{'Monday', 'Tuesday'}
Output:
{'Martin', 'David'}
Example 3:
set1 = {1,2,3,4,5,6,7}
set2 = {1,2,20,32,5,9}
set3 = set1.intersection(set2)
print(set3)
Output:
{1,2,5}
SN Method Description
1 add(item) It adds an item to the set. It has no effect if the item is already
present in the set.
4 difference_update(....) It modifies this set by removing all the items that are also
present in the specified sets.
6 intersection() It returns a new set that contains only the common elements of
both the sets. (all the sets if more than two are specified).
7 intersection_update(....) It removes the items from the original set that are not present
35
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
in both the sets (all the sets if more than one are specified).
11 pop() Remove and return an arbitrary set element that is the last
element of the set. Raises KeyError if the set is empty.