0% found this document useful (0 votes)
6 views61 pages

Python Unit 2

The document provides an overview of Python data types, focusing on built-in types such as Numeric, Sequence, Boolean, Set, Dictionary, and Binary Types. It explains how to define and manipulate lists, including operations like concatenation, repetition, and membership, as well as built-in functions for lists. Additionally, it covers tuples, their creation, indexing, and basic operations, highlighting their immutability compared to lists.

Uploaded by

muditadave.nagar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views61 pages

Python Unit 2

The document provides an overview of Python data types, focusing on built-in types such as Numeric, Sequence, Boolean, Set, Dictionary, and Binary Types. It explains how to define and manipulate lists, including operations like concatenation, repetition, and membership, as well as built-in functions for lists. Additionally, it covers tuples, their creation, indexing, and basic operations, highlighting their immutability compared to lists.

Uploaded by

muditadave.nagar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Programming [CA3EL06] Unit#2

Python Data Types




Python Data types are the classification or categorization of data


items. It represents the kind of value that tells what operations can
be performed on a particular data. Since everything is an object in
Python programming, Python data types are classes and variables
are instances (objects) of these classes. The following are the
standard or built-in data types in Python:
 Numeric
 Sequence Type
 Boolean
 Set
 Dictionary
 Binary Types( memoryview , bytearray , bytes )

What is Python Data Types?

Professor Mudita Dave Nagar Page 1


Python Programming [CA3EL06] Unit#2

To define the values of various data types of Python and check their
data types we use the type() function . Consider the following
examples.
This code assigns variable ‘x’ different values of various Python
data types. It
covers string , integer , float , complex , list , tuple , range , di
ctionary , set , frozenset , boolean , bytes , bytearray , memo
ryview , and the special value ‘None’ successively. Each
assignment replaces the previous value, making ‘x’ take on the
data type and value of the most recent assignment.
Python
x = "Hello World"
x = 50
x = 60.5
x = 3j
x = ["geeks", "for", "geeks"]
x = ("geeks", "for", "geeks")
x = range(10)
x = {"name": "Suraj", "age": 24}
x = {"geeks", "for", "geeks"}
x = frozenset({"geeks", "for", "geeks"})
x = True
x = b"Geeks"
x = bytearray(4)
x = memoryview(bytes(6))
x = None

List: Python Lists are just like dynamically sized arrays, declared in other
languages (vector in C++ and ArrayList in Java). In simple language, a list is a
collection of things, enclosed in [ ] and separated by commas.
Example of the list in Python
Here we are creating a Python List using [].

Var = ["Welcome", "to", "Medicaps"]


print(Var)

Output:
["Welcome", "to", "Medicaps"]

Access list items:

Professor Mudita Dave Nagar Page 2


Python Programming [CA3EL06] Unit#2

Print the second item of the list:

thislist = ["apple", "banana", "cherry"]


print(thislist[1])

Print the last item of the list:

thislist = ["apple", "banana", "cherry"]


print(thislist[-1])

Python List Operations


The concatenation (+) and repetition (*) operators work in the same way as
they were working with the strings. The different operations of list are

1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership

Let's see how the list responds to various operators.

1. Repetition
The redundancy administrator empowers the rundown components to be
rehashed on different occasions.

1. # repetition of list
2. # declaring the list
3. list1 = [12, 14, 16, 18, 20]
4. # repetition operator *
5. l = list1 * 2
6. print(l)

Output:

[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]

Professor Mudita Dave Nagar Page 3


Python Programming [CA3EL06] Unit#2

2. Concatenation
It concatenates the list mentioned on either side of the operator.

1. # concatenation of two lists


2. # declaring the lists
3. list1 = [12, 14, 16, 18, 20]
4. list2 = [9, 10, 32, 54, 86]

l = list1 + list2
5. print(l)

Output:

[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]

3. Length
It is used to get the length of the list

1. # size of the list


2. # declaring the list
3. list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
4. # finding length of the list
5. Print(“lenth of list is”, len(list1) )

Output:

4. Iteration
The for loop is used to iterate over the list elements.

1. # iteration of the list


2. # declaring the list
3. list1 = [12, 14, 16, 39, 40]
4. # iterating
5. for i in list1:
6. print(i)
Professor Mudita Dave Nagar Page 4
Python Programming [CA3EL06] Unit#2

Output:

12
14
16
39
40

5. Membership
It returns true if a particular item exists in a particular list otherwise false.

1. # membership of the list


2. # declaring the list
3. list1 = [100, 200, 300, 400, 500]
4. # true will be printed if value exists
5. # and false if not
6.
7. print(600 in list1)
8. print(700 in list1)
9. print(1040 in list1)
10.
11. print(300 in list1)
12. print(100 in list1)
13. print(500 in list1)

Output:

False
False
False
True
True
True

Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four
strings, which can be iterated as follows.

1. # iterating a list
2. list = ["John", "David", "James", "Jonathan"]

Professor Mudita Dave Nagar Page 5


Python Programming [CA3EL06] Unit#2

3. for i in list:
4. print(i)
Output:

John
David
James
Jonathan

Adding Elements to the List


The append() function in Python can add a new item to the List. In any case,
the annex() capability can enhance the finish of the [Link] the
accompanying model, where we take the components of the rundown from
the client and print the rundown on the control center.

1. #Declaring the empty list


2. l =[]
3. #Number of elements will be entered by the user
4. n = int(input("Enter the number of elements in the list:"))
5. # for loop to take the input
6. for i in range(0,n):
7. # The input is taken from the user and added to the list as the i
tem
8. [Link](input("Enter the item:"))
9. print("printing the list items..")
10. # traversal loop to print the list items
11. for i in l:
12. print(i, end = " ")

Output:

Enter the number of elements in the list:10


Enter the item:32
Enter the item:56
Enter the item:81
Enter the item:2
Enter the item:34
Enter the item:65
Enter the item:09
Enter the item:66
Enter the item:12

Professor Mudita Dave Nagar Page 6


Python Programming [CA3EL06] Unit#2

Enter the item:18


printing the list items..
32 56 81 2 34 65 09 66 12 18

Removing Elements from the List


The remove() function in Python can remove an element from the List. To
comprehend this idea, look at the example that follows.

Example :

1. list = [0,1,2,3,4]
2. print("printing original list: ");
3. for i in list:
4. print(i,end=" ")
5. [Link](2)
6. print("\nprinting the list after the removal of first element...")
7. for i in list:
8. print(i,end=" ")

Output:

printing original list:


0 1 2 3 4
printing the list after the removal of first element...
0 1 3 4

Python List Built-in Functions


Python provides the following built-in functions, which can be used with the
lists.

1. len()
2. max()
3. min()

len( )
It is used to calculate the length of the list.

1. # size of the list

Professor Mudita Dave Nagar Page 7


Python Programming [CA3EL06] Unit#2

2. # declaring the list


3. list1 = [12, 16, 18, 20, 39, 40]
4. # finding length of the list
5. len(list1)

Output:

Max( )
It returns the maximum element of the list

1. # maximum of the list


2. list1 = [103, 675, 321, 782, 200]
3. # large element in the list
4. print(max(list1))

Output:

782

Min( )
It returns the minimum element of the list

1. # minimum of the list


2. list1 = [103, 675, 321, 782, 200]
3. # smallest element in the list
4. print(min(list1))

Output:

103

Example: 1- Create a program to eliminate the List's duplicate items.

1. list1 = [1,2,2,3,55,98,65,65,13,29]
2. # Declare an empty list that will store unique values
3. list2 = []

Professor Mudita Dave Nagar Page 8


Python Programming [CA3EL06] Unit#2

4. for i in list1:
5. if i not in list2:
6. [Link](i)
7. print(list2)

Output:

[1, 2, 3, 55, 98, 65, 13, 29]

Example:2- Compose a program to track down the amount of the


component in the rundown.

1. list1 = [3,4,5,9,10,12,24]
2. sum = 0
3. for i in list1:
4. sum = sum+i
5. print("The sum is:",sum)

Output:

The sum is: 67


In [8]:

Example: 3- Compose the program to find the rundowns comprise of


somewhere around one normal component.

1. list1 = [1,2,3,4,5,6]
2. list2 = [7,8,9,2,10]
3. for x in list1:
4. for y in list2:
5. if x == y:
6. print("The common element is:",x)

Output:

The common element is: 2

Python offers the following list functions:

 len(): Returns the number of elements in the list.

Professor Mudita Dave Nagar Page 9


Python Programming [CA3EL06] Unit#2

 sorted(): Returns a new sorted list of the elements in the original list.
 min(): Returns the smallest element in the list.
 max(): Returns the largest element in the list.
 sum(): Returns the sum of all elements in the list.

What is Python List Method?


List methods, on the other hand, are built-in functions that are specific to the
list data type.

Python offers the following List Methods:

 append(): Adds an element to the end of the list.


 insert(): Inserts an element at a specified position in the list.
 remove(): Removes the first occurrence of an element from the list.
 pop(): Removes and returns the element at a specified index.
 sort(): Sorts the elements in the list in ascending order.

Python Tuple is a collection of objects separated by commas. In some ways,


a tuple is similar to a Python list in terms of indexing, nested objects, and
repetition but the main difference between both is Python tuple is immutable,
unlike the Python list which is mutable.

Creating Python Tuples


There are various ways by which you can create a tuple in Python. They are as
follows:
 Using round brackets
 With one item
 Tuple Constructor
Create Tuples using Round Brackets ()
To create a tuple we will use () operators.

Professor Mudita Dave Nagar Page 10


Python Programming [CA3EL06] Unit#2

var = ("Welcome", "to", "Medicaps")

print(var)

Create a Tuple With One Item


Python 3.11 provides us with another way to create a Tuple.

values : tuple[int | str, ...] = (1,2,4,"Medicaps")

print(values)

Tuple Constructor in Python


To create a tuple with a Tuple constructor, we will pass the elements as its
parameters.

tuple_constructor = tuple(("dsa", "developement", "deep learning"))

print(tuple_constructor)

Access Tuple Items

You can access tuple items by referring to the index number, inside square
brackets:

thistuple = ("apple", "banana", "cherry")


print(thistuple[1])
Negative Indexing
Negative indexing means start from the end.

-1 refers to the last item, -2 refers to the second last item etc.

Professor Mudita Dave Nagar Page 11


Python Programming [CA3EL06] Unit#2

thistuple = ("apple", "banana", "cherry")


print(thistuple[-1])

Range of Indexes
You can specify a range of indexes by specifying where to start and where to
end the range.

When specifying a range, the return value will be a new tuple with the specified
items.

Example
Return the third, fourth, and fifth item:

thistuple =
("apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango")
print(thistuple[2:5])
By leaving out the start value, the range will start at the first item:

Example
This example returns the items from the beginning to, but NOT included, "kiwi":

thistuple =
("apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango")
print(thistuple[:4])
By leaving out the end value, the range will go on to the end of the tuple:

Example
This example returns the items from "cherry" and to the end:

Professor Mudita Dave Nagar Page 12


Python Programming [CA3EL06] Unit#2

thistuple =
("apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango")
print(thistuple[2:])

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the
tuple:

Example
This example returns the items from index -4 (included) to index -1 (excluded)

thistuple =
("apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango")
print(thistuple[-4:-1])

Check if Item Exists


To determine if a specified item is present in a tuple use the in keyword:

Example
Check if "apple" is present in the tuple:

thistuple = ("apple", "banana", "cherry")


if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")

Python Tuple Operations


Here, below are the Python tuple operations.
 Accessing of Python Tuples

Professor Mudita Dave Nagar Page 13


Python Programming [CA3EL06] Unit#2

 Concatenation of Tuples
 Slicing of Tuple
 Deleting a Tuple

Accessing of Tuples
In Python Programming, Tuples are immutable, and usually, they contain a
sequence of heterogeneous elements that are accessed via unpacking or
indexing (or even by attribute in the case of named tuples). Lists are
mutable, and their elements are usually homogeneous and are accessed by
iterating over the list.
Note: In unpacking of tuple number of variables on the left-hand side should
be equal to a number of values in given tuple a.
Python
# Accessing Tuple
# with Indexing
Tuple1 = tuple("Geeks")
print("\nFirst element of Tuple: ")
print(Tuple1[0])
# Tuple unpacking
Tuple1 = ("Geeks", "For", "Geeks")
# This line unpack
# values of Tuple1
a, b, c = Tuple1
print("\nValues after unpacking: ")
print(a)
print(b)
print(c)
Output:
First element of Tuple:
G

Values after unpacking:


Geeks
For
Geeks
Time complexity: O(1)
Space complexity: O(1)
Concatenation of Tuples

Professor Mudita Dave Nagar Page 14


Python Programming [CA3EL06] Unit#2

Concatenation of tuple is the process of joining two or more Tuples.


Concatenation is done by the use of ‘+’ operator. Concatenation of tuples is
done always from the end of the original tuple. Other arithmetic operations
do not apply on Tuples.

Note- Only the same datatypes can be combined with concatenation, an


error arises if a list and a tuple are combined.

# Concatenation of tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('Geeks', 'For', 'Geeks')

Tuple3 = Tuple1 + Tuple2

# Printing first Tuple


print("Tuple 1: ")
print(Tuple1)

# Printing Second Tuple


print("\nTuple2: ")
print(Tuple2)

# Printing Final Tuple


print("\nTuples after Concatenation: ")
print(Tuple3)
Output:
Tuple 1:
(0, 1, 2, 3)

Professor Mudita Dave Nagar Page 15


Python Programming [CA3EL06] Unit#2

Tuple2:
('Geeks', 'For', 'Geeks')

Tuples after Concatenation:


(0, 1, 2, 3, 'Geeks', 'For', 'Geeks')
Time Complexity: O(1)
Auxiliary Space: O(1)
Slicing of Tuple
Slicing of a Tuple is done to fetch a specific range or slice of sub-elements
from a Tuple. Slicing can also be done to lists and arrays. Indexing in a list
results to fetching a single element whereas Slicing allows to fetch a set of
elements.
Note- Negative Increment values can also be used to reverse the sequence
of Tuples.

# Slicing of a Tuple

# Slicing of a Tuple
# with Numbers
Tuple1 = tuple('GEEKSFORGEEKS')

# Removing First element


print("Removal of First Element: ")
print(Tuple1[1:])

# Reversing the Tuple


print("\nTuple after sequence of Element is reversed: ")
print(Tuple1[::-1])

# Printing elements of a Range

Professor Mudita Dave Nagar Page 16


Python Programming [CA3EL06] Unit#2

print("\nPrinting elements between Range 4-9: ")


print(Tuple1[4:9])

Output:
Removal of First Element:
('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S')

Tuple after sequence of Element is reversed:


('S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E',
'G')

Printing elements between Range 4-9:


('S', 'F', 'O', 'R', 'G')
Time complexity: O(1)
Space complexity: O(1)
Deleting a Tuple
Tuples are immutable and hence they do not allow deletion of a part of it.
The entire tuple gets deleted by the use of del() method.
Note- Printing of Tuple after deletion results in an Error.
Python
# Deleting a Tuple

Tuple1 = (0, 1, 2, 3, 4)
del Tuple1

print(Tuple1)

Output
Traceback (most recent call last):
File "/home/[Link]", line 7, in
print(Tuple1)
NameError: name 'Tuple1' is not defined

The tuple() Function


We can use the tuple() constructor or function to create a tuple. It
basically performs two functions as follows:

 Creating an empty tuple if we give no arguments.


 Creating a tuple with elements if we pass the arguments.

Professor Mudita Dave Nagar Page 17


Python Programming [CA3EL06] Unit#2

For example,

>>>tup = tuple ((22, 45, 23, 78, 6.89))

>>>tup

(22, 45, 23, 78, 6.89)

>>> tup2 = tuple()

>>> tup2

()

The len() Function


This function returns the number of elements present in a tuple.
Moreover, it is necessary to provide a tuple to the len() function.

For example,

>>>tup = (22, 45, 23, 78, 6.89)

>>> len(tup)

The count() Function


This function will help us to fund the number of times an element is
present in the tuple. Furthermore, we have to mention the element
whose count we need to find, inside the count function.

For example,
Professor Mudita Dave Nagar Page 18
Python Programming [CA3EL06] Unit#2

>>>tup = (22, 45, 23, 78, 22, 22, 6.89)

>>> [Link](22)

>>> [Link](54)

The index() Function


The tuple index() method helps us to find the index or occurrence of an
element in a tuple. This function basically performs two functions:

 Giving the first occurrence of an element in the tuple.


 Raising an exception if the element mentioned is not found in the
tuple.
For example,

Example 1: Finding the index of an element

>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

>>> print([Link](45))

>>> print([Link](890))

#prints the index of elements 45 and 890

Example 2:

Professor Mudita Dave Nagar Page 19


Python Programming [CA3EL06] Unit#2

>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

>>> print([Link](3.2))

# gives an error because the element is not present in the


tuple.

ValueError: [Link](x): x not in tuple

The sorted() Function


This method takes a tuple as an input and returns a sorted list as an
output. Moreover, it does not make any changes to the original tuple.

For example,

>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

>>> sorted(tup)

[1, 2, 2.4, 3, 4, 22, 45, 56, 890]

The min(), max(), and sum() Tuple Functions


min(): gives the smallest element in the tuple as an output. Hence, the
name is min().

max(): gives the largest element in the tuple as an output. Hence, the
name is max().

For example,

>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

>>> max(tup)

Professor Mudita Dave Nagar Page 20


Python Programming [CA3EL06] Unit#2

890

max(): gives the sum of the elements present in the tuple as an output.

For example,

>>> tup = (22, 3, 45, 4, 2, 56, 890, 1)

>>> sum(tup)

1023

Defining a Dictionary
Dictionaries are Python’s implementation of a data structure that is more generally
known as an associative array. A dictionary consists of a collection of key-value
pairs. Each key-value pair maps the key to its associated value.

You can define a dictionary by enclosing a comma-separated list of key-value pairs


in curly braces ({}). A colon (:) separates each key from its associated value:

d={
<key>: <value>,
<key>: <value>,
.
.
.
<key>: <value>
}

Access Dictionary Values |

Professor Mudita Dave Nagar Page 21


Python Programming [CA3EL06] Unit#2



A dictionary is quite a useful data structure in Python programming that is usually


used to hash a particular key with value so that it can be retrieved efficiently.
To access an item in the dictionary, refer to its key name inside square brackets.
Example

dict = {

"country" : "India",

"continent" : "Asia",

"Other_name" : "Bharat"

x = dict["continent"]

print(x)

Output
Asia
We used a very basic and default method to access a dictionary item using
it’s key. We will discuss more advanced methods to access value in
dictionary.

How to Access Values in Dictionary


There are various ways to access items in the Dictionary or call dictionary
value, we are explaining some generally used and easy methods we use for
accessing Items (key-value) in the dictionary:
 Using key() Method
 Using values() Method
 Using an operator
 Using List Comprehension
 Using [Link]()
 Using enumerate() Method
 Using for loop and items() method

Professor Mudita Dave Nagar Page 22


Python Programming [CA3EL06] Unit#2

Printing Dictionary Using print() and str() Functions


In this example, we call dictionary value. Below Python code initializes a
dictionary named test_dict with key-value pairs. It then prints the original
dictionary using the print function and the str() function for converting the
dictionary to a string for display purposes.

# Python3 code to demonstrate

# to get key and value

# using in operator

# initializing dictionary

test_dict = {"Geeks": 1, "for": 2, "geeks": 3}

# Printing dictionary

print("Original dictionary is : " + str(test_dict))

Output :
Original dictionary is : {'Geeks': 1, 'for': 2, 'geeks': 3}

1. Access Items in Dictionary using key() Method


In Python dictionaries, the keys() method returns a view of the keys. By
iterating through this view using a for loop, you can access keys in the
dictionary efficiently. This approach simplifies key-specific
operations without the need for additional methods.
Example: In this example below code iterates through the keys of the
test_dict dictionary and prints each key along with its corresponding value.

# Accessing key-value pairs using keys() method

Professor Mudita Dave Nagar Page 23


Python Programming [CA3EL06] Unit#2

for key in test_dict.keys():

print("Key:", key, "Value:", test_dict[key])

Output :
Key: Geeks Value: 1Key: for Value: 2Key: geeks Value: 3

2. Access the Value in Dictionary using values() Method


In Python, we can access the values in a dictionary using the values()
method. This method returns a view of all values in the dictionary, allowing
you to iterate through them using a for loop or convert them to a list.
Example: In this example, the code iterates through the values of the
test_dict dictionary and prints each value.

# Accessing values using values() method

for value in test_dict.values():

print("Value:", value )

Output :
Value: 1Value: 2Value: 3

3. Access Dictionary Items using ‘in’ Operator


The most used method that can get all the keys along with its value, the “in”
operator is widely used for this very purpose and highly recommended as it
offers a concise method to achieve this task.
Example: In the example below Python code prints the key-value pairs of a
dictionary using the `in` operator. It initializes a dictionary, iterates through its
keys, and prints each key along with its corresponding value.

# using in operator to

Professor Mudita Dave Nagar Page 24


Python Programming [CA3EL06] Unit#2

# get key and value

print("Dict key-value are : ")

for i in test_dict:

print(i, test_dict[i])

Output:
Original dictionary is : {'geeks': 3, 'for': 2, 'Geeks': 1}
Dict key-value are :
geeks 3
for 2
Geeks 1

4. Access a Dictionary Items using List Comprehension


This method also uses a method similar to the above method, it just binds
the logic into one list and returns the key-value pairs of a dictionary
as tuples of key and value in the list.
Example: In this example the below code utilizes dictionary comprehension
to convert a dictionary into a list of key-value pairs using list comprehension,
demonstrating the original dictionary and the resulting list of tuples.

# using list comprehension to

# get key and value

print("Dict key-value are : ")

print([(k, test_dict[k]) for k in test_dict])

Output:
Original dictionary is : {'Geeks': 1, 'for': 2, 'geeks': 3}
Dict key-value are :
[('Geeks', 1), ('for', 2), ('geeks', 3)]

Professor Mudita Dave Nagar Page 25


Python Programming [CA3EL06] Unit#2

5. Access Items in a Dictionary Using [Link]()


Python dictionary items() method iterates over all the keys and helps us to
access the key-value pair one after the other in the loop and is also a good
method to access dictionary keys with value.
Example: In this example, the below code demonstrates how to retrieve
both keys and values from a dictionary in Python. It initializes a dictionary,
prints the original dictionary, and then uses a loop with `[Link]()` to print
each key-value pair in the dictionary.

# using [Link]() to

# get key and value

print("Dict key-value are : ")

for key, value in test_dict.items():

print(key, value)

Output:
Original dictionary is : {'geeks': 3, 'for': 2, 'Geeks': 1}
Dict key-value are :
geeks 3
for 2
Geeks 1

6. Access Items in Dictionary using enumerate()


enumerate() in Python helps to iterate over all kinds of containers, be it a
dictionary or a list. The power of this function can also be utilized to perform
this task. It also additionally helps to access the named index of the position
of the pair in the dictionary.
Example: In this example, the below code uses Python’s `enumerate()`
function to iterate over the key-value pairs of a dictionary (`test_dict`). It
prints the original dictionary and then uses `enumerate()` with `items()` to
display the key-value pairs along with their indices.

Professor Mudita Dave Nagar Page 26


Python Programming [CA3EL06] Unit#2

# using enumerate() to

# get key and value

print("Dict key-value are : ")

for i in enumerate(test_dict.items()):

print(i)

Output:
Original dictionary is : {'geeks': 3, 'Geeks': 1, 'for': 2}
Dict key-value are :
(0, ('geeks', 3))
(1, ('Geeks', 1))
(2, ('for', 2))

6. Access Values of the Dictionary using For loop and Items() Method
In Python, you can access items in a dictionary using a for loop and
the items() method. The loop iterates over key-value pairs, allowing you to
process both keys and corresponding values. This concise approach
simplifies dictionary traversal, enhancing code readability and efficiency.
Example: In this example, the below code initializes a dictionary, prints it,
and then extracts key-value pairs using a for loop and `items()`. The pairs
are stored in a list and printed, showcasing the iteration over dictionary items
for access and manipulation.

# Initializing an empty list

key_value_pairs = []

# Using a for loop to iterate over the items in the dictionary

Professor Mudita Dave Nagar Page 27


Python Programming [CA3EL06] Unit#2

# and append each key-value pair to the list

for key, value in test_dict.items():

key_value_pairs.append((key, value))

# Printing the key-value pairs

print("Dict key-value are : ")

for pair in key_value_pairs:

print(pair)

Output:
Original dictionary is : {'Geeks': 1, 'for': 2, 'geeks': 3}
Dict key-value are :
('Geeks', 1)
('for', 2)
('geeks', 3)

Working with dictionary:

Create a Dictionary
We create a dictionary by placing key: value pairs inside curly brackets {} ,

separated by commas. For example,


# creating a dictionary
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
"England": "London"
}

Professor Mudita Dave Nagar Page 28


Python Programming [CA3EL06] Unit#2

# printing the dictionary


print(country_capitals)
Run Code

Output

{'Germany': 'Berlin', 'Canada': 'Ottawa', 'England': 'London'}

Access Dictionary Items


We can access the value of a dictionary item by placing the key inside square
brackets.

country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
"England": "London"
}

# access the value of keys


print(country_capitals["Germany"]) # Output: Berlin
print(country_capitals["England"]) # Output: London

Add Items to a Dictionary


We can add an item to a dictionary by assigning a value to a new key. For
example,

country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
}

# add an item with "Italy" as key and "Rome" as its value


country_capitals["Italy"] = "Rome"

Professor Mudita Dave Nagar Page 29


Python Programming [CA3EL06] Unit#2

print(country_capitals)

Remove Dictionary Items


We can use the del statement to remove an element from a dictionary. For
example,
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
}

# delete item having "Germany" key


del country_capitals["Germany"]

print(country_capitals)

Output

{'Canada': 'Ottawa'}

If we need to remove all items from a dictionary at once, we can use


the clear() method.
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
}

# clear the dictionary


country_capitals.clear()

print(country_capitals)

Output

{}

Professor Mudita Dave Nagar Page 30


Python Programming [CA3EL06] Unit#2

Change Dictionary Items


Python dictionaries are mutable (changeable). We can change the value of a
dictionary element by referring to its key. For example,

country_capitals = {
"Germany": "Berlin",
"Italy": "Naples",
"England": "London"
}

# change the value of "Italy" key to "Rome"


country_capitals["Italy"] = "Rome"

print(country_capitals)

Output

{'Germany': 'Berlin', 'Italy': 'Rome', 'England': 'London'}

Note: We can also use the update() method to add or change dictionary
items.

Iterate Through a Dictionary


A dictionary is an ordered collection of items (starting from Python 3.7),
therefore it maintains the order of its items.

We can iterate through dictionary keys one by one using a for loop.
country_capitals = {
"United States": "Washington D.C.",

Professor Mudita Dave Nagar Page 31


Python Programming [CA3EL06] Unit#2

"Italy": "Rome"
}

# print dictionary keys one by one


for country in country_capitals:
print(country)

print()

# print dictionary values one by one


for country in country_capitals:
capital = country_capitals[country]
print(capital)

Output

United States
Italy

Washington D.C.
Rome

Find Dictionary Length


We can find the length of a dictionary by using the len() function.
country_capitals = {"England": "London", "Italy": "Rome"}

# get dictionary's length


print(len(country_capitals)) # Output: 2

numbers = {10: "ten", 20: "twenty", 30: "thirty"}

# get dictionary's length


print(len(numbers)) # Output: 3

countries = {}

# get dictionary's length


print(len(countries)) # Output: 0

Professor Mudita Dave Nagar Page 32


Python Programming [CA3EL06] Unit#2

Creating a Python Dictionary


A Dictionary can be formed in Python by assigning a sequence of
entries enclosed by curly braces {} and separated by a comma.
Dictionary stores a pair of values, one of which is the Key and the other
being the key:value pair element. While values can be of any data type
and repeated, keys must be immutable (string, number, or tuple with
immutable elements) and unique, i.e. they cannot be repeated.

The general syntax followed to create Python dictionary is as follows:

dictionary_name = {key_1: value_1, key_2: value_2, key_3:


value_3}

Or Python dictionary can be created using the dict() in-built function


provided by Python.

For example

Copy Code

# Python program to create a dictionary


# empty dictionary
my_dict = {}
print(my_dict)

# dictionary with keys as integers


my_dict = {1: 'One', 2: 'Two', 3: 'Three'}
print(my_dict)

# dictionary with mixed keys


my_dict = {'Name': 'John', 'Age': 24, 1: [2, 4, 3]}
print(my_dict)

# using dict()
my_dict = dict({1:'One', 2:'Two'})
print(my_dict)
Professor Mudita Dave Nagar Page 33
Python Programming [CA3EL06] Unit#2

# from sequence having each item as a pair


my_dict = dict([(1,'John'), (2,'David')])
print(my_dict)

Output

{}
{1: 'One', 2: 'Two', 3: 'Three'}
{'Name': 'John', 'Age': 24, 1: [2, 4, 3]}
{1: 'One', 2: 'Two'}
{1: 'John', 2: 'David'}

Accessing Elements from Dictionary


Because Dictionaries are an unordered collection of iterables, a value
within it cannot be accessed using an index; instead, a key must be
supplied in square brackets. Keys can be used with either square
brackets [] or the get() method.

If we use square brackets [], we get a KeyError if a key is not found in


the dictionary. The get() method, on the other hand, returns None if the
key is not found.

Example

Copy Code

# Python program to access elements from a dictionary


my_dict = {'Name': 'Sean', 'Age': 24, 'Hobby': 'Dancing',
'City': 'NY'}

# using square brackets


print(my_dict['Name'])
print(my_dict['Age'])

# using get() method

Professor Mudita Dave Nagar Page 34


Python Programming [CA3EL06] Unit#2

print(my_dict.get('Hobby'))

# key not found


print(my_dict.get('Salary'))

# error raised when key not found


print(my_dict['Occupation'])

Output

Sean
24
Dancing
None

Traceback (most recent call last):


File "", line 15, in
KeyError: 'Occupation'

Changing and Adding Dictionary elements


Dictionaries are subject to change. Using an assignment operator, we
can add new things or change the value of existing items. By declaring
value together with the key, for example, Dict[Key] = ‘Value’, one
value at a time can be added to a Dictionary. Another approach is to use
Python’s update() function.

Note – If the key-value pair is already in the dictionary, the value is


updated. In the absence of this, a new key:value pair is added to the
dictionary.

Example

Copy Code

# Python program to update/add elements in a dictionary


my_dict = {'Car': 'Audi', 'Bike': 'Honda'}
Professor Mudita Dave Nagar Page 35
Python Programming [CA3EL06] Unit#2

print('Original Dictionary:', my_dict)

# updating value of an existing key


my_dict['Bike'] = 'Ducati'
print('Updated Dictionary:', my_dict)

# adding new value


my_dict['Plane'] = 'Boeing'
print('Updated Dictionary:', my_dict)

Output

Original Dictionary: {'Car': 'Audi', 'Bike': 'Honda'}


Updated Dictionary: {'Car': 'Audi', 'Bike': 'Ducati'}
Updated Dictionary: {'Car': 'Audi', 'Bike': 'Ducati',
'Plane': 'Boeing'}

Removing elements from Dictionary


A key can be removed from a dictionary in three ways: from an
individual entry, from all entries, or from the entire dictionary.

1. The pop() function can be used to remove a single element. The


value of the key that has been specified to be eliminated is returned
by the pop() function.
2. To randomly remove any elements (key-value pairs) of the
dictionary, we can use the popitem() It returns the arbitrary key-
value pair that has been removed from the dictionary.
3. Using the clear() method, all elements can be eliminated at once.
4. The del keyword is used to completely delete the entire dictionary.
Example

# Python program to remove/delete elements from a


dictionary
Professor Mudita Dave Nagar Page 36
Python Programming [CA3EL06] Unit#2

my_dict = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5:


'Five'}
print('Original Dictionary:', my_dict)

# removing single element


print(my_dict.pop(4))
print('Updated Dictionary:', my_dict)

# adding new value


print(my_dict.popitem())
print('Updated Dictionary:', my_dict)

# remove all items


my_dict.clear()
print(my_dict)

# delete the dictionary itself


del my_dict
print(my_dict)

Output

Original Dictionary: {1: 'One', 2: 'Two', 3: 'Three', 4:


'Four', 5: 'Five'}
Four
Updated Dictionary: {1: 'One', 2: 'Two', 3: 'Three', 5:
'Five'}
(5, 'Five')
Updated Dictionary: {1: 'One', 2: 'Two', 3: 'Three'}
{}

Traceback (most recent call last):


File "", line 19, in
NameError: name 'my_dict' is not defined

Python Dictionary Methods

Professor Mudita Dave Nagar Page 37


Python Programming [CA3EL06] Unit#2

The Python dictionary provides a variety of methods and functions that


can be used to easily perform operations on the key-value pairs. Python
dictionary methods are listed below.

Method Description

clear() Removes all the elements from the dictionary

copy() Returns a shallow copy of the specified dictionary

Creates a new dictionary with keys from seq and val


fromkeys(seq, val)
assigned to all the keys

get(key) Returns the value of the specified key

Returns True if the key exists in the dictionary, else returns


has_key()
False

items() Returns a list of dictionary’s items in (key, value) format pairs

keys() Returns a list containing all the keys in the dictionary

pop(key) Removes and returns an element from a dictionary having

Professor Mudita Dave Nagar Page 38


Python Programming [CA3EL06] Unit#2

the given key

popitem() Removes and returns an arbitrary item (key, value).

Returns the corresponding value if the key is in the


setdefault(key, val)
dictionary. If not, inserts the key with a value of val

update() Updates the dictionary by adding key-value pair

values() Returns a list containing all the values in the dictionary

Let us look at few examples of these Python dictionary methods.

# Dictionary Methods
my_dict = {}
age = my_dict.fromkeys(['John', 'Emily', 'Tina'], 20)
print(age)

print('Keys in the dictionary are:', list([Link]()))


print('Values in the dictionary are:', list([Link]()))

print('Age value of John:', [Link]('John'))

Output

{'John': 20, 'Emily': 20, 'Tina': 20}


Keys in the dictionary are: ['John', 'Emily', 'Tina']
Values in the dictionary are: [20, 20, 20]
Age value of John: 20

Professor Mudita Dave Nagar Page 39


Python Programming [CA3EL06] Unit#2

Python Dictionary Comprehension


In Python, dictionary comprehension is a simple and beautiful approach
to generate a new dictionary from an iterable. Dictionary
comprehension is made up of an expression pair (key: value) followed
by a for statement enclosed in curly braces. Here’s an example of a
dictionary where each item is a pair of a number and its square.

Example

# Dictionary Comprehension
multiple = {x: x*2 for x in range(5)}
print(multiple)

Output

{0: 0, 1: 2, 2: 4, 3: 6, 4: 8}

The above code is equivalent to:

multiple = {}
for x in range(5):
multiple[x] = x*2
print(multiple)

Output

{0: 0, 1: 2, 2: 4, 3: 6, 4: 8}

Other Dictionary Operations


 Dictionary Membership Test

What if we want to check if a specific key is present in the dictionary?


Using the keyword ‘in’ and ‘not in’, we can determine whether a key is
Professor Mudita Dave Nagar Page 40
Python Programming [CA3EL06] Unit#2

in a dictionary or not. It’s worth noting that the membership test only
applies to keys, and not values.

Example

# Membership Test for Dictionary Keys


results = {'Sam': 'Pass', 'Zac': 'Pass', 'Lily': 'Fail',
'Casey': 'Pass'}

print('Lily' in results) # returns True


print('Rocky' in results) # returns False

print('Ella' not in results) # returns True

# membership tests for key only not value, returns False


print('Pass' in results)

Output

True
False
True
False

 Iterating Through a Dictionary

Using a for loop, we can traverse through each key, value or both in a
dictionary. For example,

# Iterating through a Dictionary


course = {'Sam': 'MBA', 'Zac': 'MS', 'Lily': 'BBA',
'Casey': 'Architecture'}

for i in course:
print(course[i])
print('')

Professor Mudita Dave Nagar Page 41


Python Programming [CA3EL06] Unit#2

# printing keys and values


for i,j in [Link]():
print(i, '->', j)

Output

MBA
MS
BBA
Architecture

Sam -> MBA


Zac -> MS
Lily -> BBA
Casey -> Architecture

 Dictionary Built-in Functions

Built-in functions such as all(), any(), len(), cmp(), sorted(), and others
are frequently used with Python dictionaries to complete various tasks.

Function Description

Returns value True if all the keys in the dictionary are true
all()
or if the dictionary is empty

Returns True if any of the key in the dictionary is True. If


any()
the dictionary is empty it returns False

len() Returns the number of items in the dictionary

cmp() Used to compare items of 2 dictionaries

Professor Mudita Dave Nagar Page 42


Python Programming [CA3EL06] Unit#2

sorted() Returns a sorted list of keys in the dictionary

Example

# Dictionary Built-in Functions


my_dict = {0: 'Zero', 1: 'One', 2: 'Two', 3: 'Three'}

print(all(my_dict))

print(any(my_dict))

print(len(my_dict))

print(sorted(my_dict))

Output

False
True
4
[0, 1, 2, 3]

Python String


A String is a data structure in Python Programming that represents a


sequence of characters. It is an immutable data type, meaning that
once you have created a string, you cannot change it. Python String
are used widely in many different applications, such as storing and

Professor Mudita Dave Nagar Page 43


Python Programming [CA3EL06] Unit#2

manipulating text data, representing names, addresses, and other


types of data that can be represented as text.

What is a String in Python?


Python Programming does not have a character data type, a single character
is simply a string with a length of 1.
syntax:

Syntax of String Data Type in Python


string_variable = 'Hello, world!'
Example of string data type in Python

string_0 = "A Computer Science portal for geeks"


print(string_0)
print(type(string_0))
Output:
A Computer Science portal for geeks
<class 'str'>
Create a String in Python
Strings in Python can be created using single quotes or double quotes or
even triple quotes. Let us see how we can define a string in Python or how to
write string in Python.
Example:
In this example, we will demonstrate different ways to create a Python String.
We will create a string using single quotes (‘ ‘), double quotes (” “), and triple
double quotes (“”” “””). The triple quotes can be used to declare multiline
strings in Python.

# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)

# Creating a String

Professor Mudita Dave Nagar Page 44


Python Programming [CA3EL06] Unit#2

# with triple Quotes


String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)

# Creating String with triple


# Quotes allows multiple lines
String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)
Output:
String with the use of Single Quotes:
Welcome to the Geeks World
String with the use of Double Quotes:
I'm a Geek
String with the use of Triple Quotes:
I'm a Geek and I live in a world of "Geeks"
Creating a multiline String:
Geeks
For
Life
Accessing characters in Python String
In Python Programming tutorials, individual characters of a String can be
accessed by using the method of Indexing. Indexing allows negative address
references to access characters from the back of the String, e.g. -1 refers to
the last character, -2 refers to the second last character, and so on.
While accessing an index out of the range will cause an IndexError. Only
Integers are allowed to be passed as an index, float or other types that will
cause a TypeError.

Python String syntax indexing

Professor Mudita Dave Nagar Page 45


Python Programming [CA3EL06] Unit#2

Python String Positive Indexing


In this example, we will define a string in Python Programming and access
its characters using positive indexing. The 0th element will be the first
character of the string.
Python

String1 = "GeeksForGeeks"
print("Initial String: ", String1)

# Printing First character


print("First character of String is: ", String1[0])
Output:
Initial String: GeeksForGeeks
First character of String is: G
Python String Negative Indexing
In this example, we will access its characters using negative indexing. The -
3th element is the third last character of the string.
Python

String1 = "GeeksForGeeks"
print("Initial String: ", String1)

# Printing Last character


print("Last character of String is: ", String1[-3])
Output
Initial String: GeeksForGeeks
Last character of String is: e
String Slicing Python
In Python Programming tutorials, the String Slicing method is used to access
a range of characters in the String. Slicing in a String is done by using a
Slicing operator, i.e., a colon (:). One thing to keep in mind while using this
method is that the string returned after slicing includes the character at the
start index but not the character at the last index.
In this example, we will use the string-slicing method to extract a substring of
the original string. The [3:12] indicates that the string slicing will start from
the 3rd index of the string to the 12th index, (12th character not including).
We can also use negative indexing in string slicing.
Python

# Creating a String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)

Professor Mudita Dave Nagar Page 46


Python Programming [CA3EL06] Unit#2

# Printing 3rd to 12th character


print("\nSlicing characters from 3-12: ")
print(String1[3:12])

# Printing characters between


# 3rd and 2nd last character
print("\nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])
Output:
Initial String:
GeeksForGeeks
Slicing characters from 3-12:
ksForGeek
Slicing characters between 3rd and 2nd last character:
ksForGee
Python String Reversed
In Python Programming tutorials, By accessing characters from a string, we
can also reverse strings in Python Programming. We can Reverse a string by
using String slicing method.
In this example, we will reverse a string by accessing the index. We did not
specify the first two parts of the slice indicating that we are considering the
whole string, from the start index to the last index.
Python

#Program to reverse a string


gfg = "geeksforgeeks"
print(gfg[::-1])
Output:
skeegrofskeeg
BuildIn Reverse Function in Python
We can also reverse a string by using built-in join and reversed functions,
and passing the string as the parameter to the reversed() function.
Python

# Program to reverse a string

gfg = "geeksforgeeks"

# Reverse the string using reversed and join function


gfg = "".join(reversed(gfg))

print(gfg)
Output:
skeegrofskeeg

Professor Mudita Dave Nagar Page 47


Python Programming [CA3EL06] Unit#2

Deleting/Updating from a String


In Python, the Updation or deletion of characters from a String is not allowed.
This will cause an error because item assignment or item deletion from a
String is not supported. Although deletion of the entire String is possible with
the use of a built-in del keyword. This is because Strings are immutable,
hence elements of a String cannot be changed once assigned. Only new
strings can be reassigned to the same name.
Updating a character
A character of a string can be updated in Python by first converting the string
into a Python List and then updating the element in the list. As lists are
mutable in nature, we can update the character and then convert the list
back into the String.
Another method is using the string slicing method. Slice the string before the
character you want to update, then add the new character and finally add the
other part of the string again by string slicing.
Example:
In this example, we are using both the list and the string slicing method to
update a character. We converted the String1 to a list, changes its value at a
particular element, and then converted it back to a string using the
Python string join() method.
In the string-slicing method, we sliced the string up to the character we want
to update, concatenated the new character, and finally concatenate the
remaining part of the string.
Python

# Python Program to Update


# character of a String

String1 = "Hello, I'm a Geek"


print("Initial String: ")
print(String1)

# Updating a character of the String


## As python strings are immutable, they don't support item updation
directly
### there are following two ways
#1
list1 = list(String1)
list1[2] = 'p'
String2 = ''.join(list1)
print("\nUpdating character at 2nd Index: ")
print(String2)

#2

Professor Mudita Dave Nagar Page 48


Python Programming [CA3EL06] Unit#2

String3 = String1[0:2] + 'p' + String1[3:]


print(String3)
Output:
Initial String:
Hello, I'm a Geek
Updating character at 2nd Index:
Heplo, I'm a Geek
Heplo, I'm a Geek
Updating Entire String
In Python Programming, As Python strings are immutable in nature, we
cannot update the existing string. We can only assign a completely new
value to the variable with the same name.
Example: In this example, we first assign a value to ‘String1’ and then
updated it by assigning a completely different value to it. We simply changed
its reference.
Python

# Python Program to Update


# entire String

String1 = "Hello, I'm a Geek"


print("Initial String: ")
print(String1)

# Updating a String
String1 = "Welcome to the Geek World"
print("\nUpdated String: ")
print(String1)
Output:
Initial String:
Hello, I'm a Geek
Updated String:
Welcome to the Geek World
Deleting a character
Python strings are immutable, that means we cannot delete a character from
it. When we try to delete thecharacter using the del keyword, it will generate
an error.
Python

# Python Program to delete


# character of a String

String1 = "Hello, I'm a Geek"


print("Initial String: ")
print(String1)

Professor Mudita Dave Nagar Page 49


Python Programming [CA3EL06] Unit#2

print("Deleting character at 2nd Index: ")


del String1[2]
print(String1)
Output:
Initial String:
Hello, I'm a Geek
Deleting character at 2nd Index:
Traceback (most recent call last):
File "e:\GFG\Python codes\Codes\[Link]", line 9, in <module>
del String1[2]
TypeError: 'str' object doesn't support item deletion
But using slicing we can remove the character from the original string and
store the result in a new string.
Example: In this example, we will first slice the string up to the character that
we want to delete and then concatenate the remaining string next from the
deleted character.
Python

# Python Program to Delete


# characters from a String

String1 = "Hello, I'm a Geek"


print("Initial String: ")
print(String1)

# Deleting a character
# of the String
String2 = String1[0:2] + String1[3:]
print("\nDeleting character at 2nd Index: ")
print(String2)
Output:
Initial String:
Hello, I'm a Geek
Deleting character at 2nd Index:
Helo, I'm a Geek
Deleting Entire String
In Python Programming, Deletion of the entire string is possible with the use
of del keyword. Further, if we try to print the string, this will produce an error
because the String is deleted and is unavailable to be printed.
Python

# Python Program to Delete


# entire String

String1 = "Hello, I'm a Geek"

Professor Mudita Dave Nagar Page 50


Python Programming [CA3EL06] Unit#2

print("Initial String: ")


print(String1)

# Deleting a String
# with the use of del
del String1
print("\nDeleting entire String: ")
print(String1)
Error:
Traceback (most recent call last):
File "/home/[Link]", line 12, in
print(String1)
NameError: name 'String1' is not defined
Escape Sequencing in Python
While printing Strings with single and double quotes in it
causes SyntaxError because String already contains Single and Double
Quotes and hence cannot be printed with the use of either of these. Hence,
to print such a String either Triple Quotes are used or Escape sequences are
used to print Strings.
Escape sequences start with a backslash and can be interpreted differently.
If single quotes are used to represent a string, then all the single quotes
present in the string must be escaped and the same is done for Double
Quotes.
Python

# Initial String
String1 = '''I'm a "Geek"'''
print("Initial String with use of Triple Quotes: ")
print(String1)

# Escaping Single Quote


String1 = 'I\'m a "Geek"'
print("\nEscaping Single Quote: ")
print(String1)

# Escaping Double Quotes


String1 = "I'm a \"Geek\""
print("\nEscaping Double Quotes: ")
print(String1)

# Printing Paths with the


# use of Escape Sequences
String1 = "C:\\Python\\Geeks\\"
print("\nEscaping Backslashes: ")
print(String1)

Professor Mudita Dave Nagar Page 51


Python Programming [CA3EL06] Unit#2

# Printing Paths with the


# use of Tab
String1 = "Hi\tGeeks"
print("\nTab: ")
print(String1)

# Printing Paths with the


# use of New Line
String1 = "Python\nGeeks"
print("\nNew Line: ")
print(String1)
Output:
Initial String with use of Triple Quotes:
I'm a "Geek"
Escaping Single Quote:
I'm a "Geek"
Escaping Double Quotes:
I'm a "Geek"
Escaping Backslashes:
C:\Python\Geeks\
Tab:
Hi Geeks
New Line:
Python
Geeks
Example:
To ignore the escape sequences in a String, r or R is used, this implies that
the string is a raw string and escape sequences inside it are to be ignored.
Python

# Printing hello in octal


String1 = "\110\145\154\154\157"
print("\nPrinting in Octal with the use of Escape Sequences: ")
print(String1)

# Using raw String to


# ignore Escape Sequences
String1 = r"This is \110\145\154\154\157"
print("\nPrinting Raw String in Octal Format: ")
print(String1)

# Printing Geeks in HEX


String1 = "This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"
print("\nPrinting in HEX with the use of Escape Sequences: ")
print(String1)

# Using raw String to

Professor Mudita Dave Nagar Page 52


Python Programming [CA3EL06] Unit#2

# ignore Escape Sequences


String1 = r"This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"
print("\nPrinting Raw String in HEX Format: ")
print(String1)
Output:
Printing in Octal with the use of Escape Sequences:
Hello
Printing Raw String in Octal Format:
This is \110\145\154\154\157
Printing in HEX with the use of Escape Sequences:
This is Geeks in HEX
Printing Raw String in HEX Format:
This is \x47\x65\x65\x6b\x73 in \x48\x45\x58
Python String Formatting
Strings in Python or string data type in Python can be formatted with the use
of format() method which is a very versatile and powerful tool for formatting
Strings. Format method in String contains curly braces {} as placeholders
which can hold arguments according to position or keyword to specify the
order.
Example 1: In this example, we will declare a string which contains the curly
braces {} that acts as a placeholders and provide them values to see how
string declaration position matters.
Python

# Python Program for


# Formatting of Strings

# Default order
String1 = "{} {} {}".format('Geeks', 'For', 'Life')
print("Print String in default order: ")
print(String1)

# Positional Formatting
String1 = "{1} {0} {2}".format('Geeks', 'For', 'Life')
print("\nPrint String in Positional order: ")
print(String1)

# Keyword Formatting
String1 = "{l} {f} {g}".format(g='Geeks', f='For', l='Life')
print("\nPrint String in order of Keywords: ")
print(String1)
Output:
Print String in default order:
Geeks For Life
Print String in Positional order:
For Geeks Life
Professor Mudita Dave Nagar Page 53
Python Programming [CA3EL06] Unit#2

Print String in order of Keywords:


Life For Geeks
Example 2: Integers such as Binary, hexadecimal, etc., and floats can be
rounded or displayed in the exponent form with the use of format specifiers.
Python

# Formatting of Integers
String1 = "{0:b}".format(16)
print("\nBinary representation of 16 is ")
print(String1)

# Formatting of Floats
String1 = "{0:e}".format(165.6458)
print("\nExponent representation of 165.6458 is ")
print(String1)

# Rounding off Integers


String1 = "{0:.2f}".format(1/6)
print("\none-sixth is : ")
print(String1)
Output:
Binary representation of 16 is
10000
Exponent representation of 165.6458 is
1.656458e+02
one-sixth is :
0.17
Example 3: In String data type in Python , A string can be left, right, or
center aligned with the use of format specifiers, separated by a colon(:). The
(<) indicates that the string should be aligned to the left, (>) indicates that the
string should be aligned to the right and (^) indicates that the string should
be aligned to the center. We can also specify the length in which it should be
aligned. For example, (<10) means that the string should be aligned to the
left within a field of width of 10 characters.
Python

# String alignment
String1 = "|{:<10}|{:^10}|{:>10}|".format('Geeks',
'for',
'Geeks')
print("\nLeft, center and right alignment with Formatting: ")
print(String1)

# To demonstrate aligning of spaces


String1 = "\n{0:^16} was founded in {1:<4}!".format("GeeksforGeeks",
2009)
print(String1)

Professor Mudita Dave Nagar Page 54


Python Programming [CA3EL06] Unit#2

Output:
Left, center and right alignment with Formatting:
|Geeks | for | Geeks|
GeeksforGeeks was founded in 2009 !
Example 4: Old-style formatting was done without the use of the format
method by using the % operator
Python

# Python Program for


# Old Style Formatting
# of Integers

Integer1 = 12.3456789
print("Formatting in 3.2f format: ")
print('The value of Integer1 is %3.2f' % Integer1)
print("\nFormatting in 3.4f format: ")
print('The value of Integer1 is %3.4f' % Integer1)
Output:
Formatting in 3.2f format:
The value of Integer1 is 12.35
Formatting in 3.4f format:
The value of Integer1 is 12.3457
Case Changing of Python String Methods
The below Python functions are used to change the case of the strings. Let’s
look at some Python string methods with examples:
 lower(): Converts all uppercase characters in a string into lowercase
 upper(): Converts all lowercase characters in a string into uppercase
 title(): Convert string to title case
 swapcase(): Swap the cases of all characters in a string
 capitalize(): Convert the first character of a string to uppercase
Example: Changing the case of Python String Methods
Python
# Python3 program to show the
# working of upper() function
text = 'geeKs For geEkS'

# upper() function to convert


# string to upper case
print("\nConverted String:")
print([Link]())

# lower() function to convert


# string to lower case
print("\nConverted String:")
print([Link]())

Professor Mudita Dave Nagar Page 55


Python Programming [CA3EL06] Unit#2

# converts the first character to


# upper case and rest to lower case
print("\nConverted String:")
print([Link]())

# swaps the case of all characters in the string


# upper case character to lowercase and viceversa
print("\nConverted String:")
print([Link]())

# convert the first character of a string to uppercase


print("\nConverted String:")
print([Link]())

# original string never changes


print("\nOriginal String")
print(text)

Output
Converted String:
GEEKS FOR GEEKS

Converted String:
geeks for geeks

Converted String:
Geeks For Geeks

Converted String:
GEEkS fOR GEeKs

Original String
geeKs For geEkS

Professor Mudita Dave Nagar Page 56


Python Programming [CA3EL06] Unit#2

7 Useful String Functions in Python


1. Capitalize

The capitalize() is used in Python where the first letter of the string is
converted into UPPERCASE and the rest of the characters remain the same.
On the other hand, if all the characters are in UPPERCASE then the string
will return the same value (except the first character).
Example: mY name is YUVRAJ -> My name is yuvraj

# input from users

sentence_1 = "mY name is YUVRAJ"

sentence_2 = "MY name is Ansul"

# Convert case using capitalize()

capitalized_string = sentence_1.capitalize()

print("Sentence 1 output -> ", capitalized_string)

capitalized_string = sentence_2.capitalize()

print("Sentence 2 output -> ", capitalized_string)

Output:
Sentence 1 output -> My name is yuvraj
Sentence 2 output -> My name is ansul

2. Count

The count() is used in Python to count the number of occurrences of an


individual element or substring that appears within the string. The count()

Professor Mudita Dave Nagar Page 57


Python Programming [CA3EL06] Unit#2

throws the numeric value that provides the detail of an actual count of a
given string.
Example: GFG KARLO HO JAYEGA -> Count of ‘G’ = 3

message = 'GFG KARLO HO JAYEGA'

# number of occurrence of 'G'

print('Number of occurrence of G:', [Link]('G'))

Output:
Number of occurrence of G: 3

3. Find

The find() is used in Python to return the lowest index value from the first
occurrence of a string (only in case if its found): else the value would be -1.
Example: Yuvraj is my name -> Position of ‘is’ = 7
 Python3

message = 'Yuvraj is my name'

# check the index of 'is'

print([Link]('is'))

Output:
7

Professor Mudita Dave Nagar Page 58


Python Programming [CA3EL06] Unit#2

4. Lower

The lower() is used in Python programming to ensure that all the


UPPERCASE characters in the string are converted into lowercase and
fetched with a new lowercase string and the original copy of the string
remains intact.
Example: GEEKSFORGEEKS IS A COMPUTER SCIENCE PORTAL -
> ‘geeksforgeeks is a computer science portal’

message = 'GEEKSFORGEEKS IS A COMPUTER SCIENCE PORTAL'

# convert message to lowercase

print([Link]())

Output:
geeksforgeeks is a computer science portal

5. Upper

The upper() is used in Python programming to ensure that all the lowercase
characters in the string are converted into UPPERCASE and fetched with a
new string whereas the original copy of the string remains intact.
Example: geeksforgeeks is a computer science portal -
> GEEKSFORGEEKS IS A COMPUTER SCIENCE PORTAL

message = 'geeksforgeeks is a computer science portal'

# convert message to uppercase

Professor Mudita Dave Nagar Page 59


Python Programming [CA3EL06] Unit#2

print([Link]())

Output:
GEEKSFORGEEKS IS A COMPUTER SCIENCE PORTAL

6. Replace

The replace() is used in Python to replace any unwanted character or text


and replace it with the new desired output within the string. The replace() can
be used in Python with the below-mentioned syntax to perform the action:
[Link](old, new, count)
Example: subway surfer -> Replace ‘s’ with ‘t’ = tubway turfer

text = 'subway surfer'

# replace s with t

replaced_text = [Link]('s', 't')

print(replaced_text)

Output:
tubway turfer

7. Join

The join() is used in Python programming to merge each element of an


iterable such as a list, set, etc., and later you can use a string separator to
separate the values. Thus, join() returns a concatenated string and it will
throw a TypeError exception if the iterable contains any non-string element
within it.

text = ['Anshul', 'is', 'my', 'only', 'friend']

Professor Mudita Dave Nagar Page 60


Python Programming [CA3EL06] Unit#2

# join elements of text with space

print(' '.join(text))

Output:
Anshul is my only friend

--------------------------------------End of Unit-II-----------------------------------------------------------

Professor Mudita Dave Nagar Page 61

You might also like