Amity University Jharkhand, Ranchi
CSE 205
Programming in Python
Amity University Jharkhand, Ranchi
Python Data Type
Python data type is categorized into two types:
•Mutable Data Type – A mutable data type is those whose values can be
changed.
• Example: List, Dictionaries, and Set
•Immutable Data Type – An immutable data type is one in which the values
can’t be changed or altered.
• Example: String and Tuples
Amity University Jharkhand, Ranchi
Changing individual characters of a string
Suppose we have a string called s and we want to change the character at index 4 of s to
'X'. It is tempting to try s[4]='X', but that unfortunately will not work. Python strings are
immutable, which means we can’t modify any part of them.
s="Testing"
print(s[:4] + 'X' + s[5:]);
Looping
Very often we will want to scan through a string one character at a time. A for loop
like the one below can be used to do that.
s="Testing"
for i in range(len(s)):
print (s[i])
In the range statement we have len(s) that returns how long s is.
Amity University Jharkhand, Ranchi
String methods
Strings come with a ton of methods, functions that return information about the
string or return a new string that is a modified version of the original.
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
String Methods (String Manipulation)
String manipulation is very useful and very widely used in every language.
Often, programmers are required to break down strings and examine them
closely.
For example, a password strength checker would have to strip a string down and
examine them closely to see if it contains letters, numbers and/or symbols.
Amity University Jharkhand, Ranchi
String Methods (String Manipulation)
• This presentation will take a look at the various
methods of manipulating strings, covering things from
basic methods to regular expressions in Python.
• String manipulation is a skill that every Python
programmer should be familiar with.
Amity University Jharkhand, Ranchi
String Methods (String Manipulation)
We can perform a number of tasks on strings through these methods.
The most basic way to manipulate strings is through the methods that are built into
Python.
Amity University Jharkhand, Ranchi
String Methods (String Manipulation)
We can perform:
String Checks:
- Find the length of a string
- Find out if a string is all in uppercase
- find out if a string is all in lowercase
- find out if a string’s words all start with capitals letters
- Check whether a string is alphanumeric(contains both letters and numbers)
- Check whether a string contains only numbers
- Check whether a string contains only letters
- Check whether a string only contains spaces
- Find the location of a character in a string
- Count how many times a character appears in a string String Formatting Methods:
- Turn a string upper case
- Turn a string lower case
String to Lists Conversions: - Capitalize a string (make first letter capital)
- Capitalize each word in a string
- Split a string into a number of items on a list
- Swap the case of each letter in a string around
- Add spaces in either side of a string.
Other Useful String Methods:
- Return the character at a certain position of a string
- Replace letters and words in a string
Amity University Jharkhand, Ranchi
This simply means ‘joining’.
We know from before that the ‘+’ operator is used to add numeric data types
together.
This operator has a different function when it deals with strings. The ‘+’ sign
simply joins together two or more string.
full_name_no_space = firstname + surname
Example:
Full_name = firstname + “ ” + surname
Amity University Jharkhand, Ranchi
Find the length of a string
The len function:
This helps us find the length
of a string (how many
characters it has – including
spaces)
Or
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Look at each character of string in turn
Amity University Jharkhand, Ranchi
Find out if a string is all in uppercase
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Check whether a string is alphanumeric (contains
only letters and numbers)
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Other useful string manipulation
functions
Amity University Jharkhand, Ranchi
String Formatting Methods
Amity University Jharkhand, Ranchi
Or
Amity University Jharkhand, Ranchi
Or
Amity University Jharkhand, Ranchi
Or
Amity University Jharkhand, Ranchi
Or
Amity University Jharkhand, Ranchi
Or
Amity University Jharkhand, Ranchi
Add spaces to indent or centre strings on screen.
Amity University Jharkhand, Ranchi
Pretty Printing
[Link]() method
Here is an example of
how the variables
(contained in the format
function’s brackets) is
printed according to
some pretty printing
rules.
For digits:
{0:2d} {1:3d} {2:4d}
means, in the first
column (0) allow for 2
digits, in the second
column (1) allow for 3
digits etc.
For strings:
{0:10} means, in the first
column, allow for 10
characters.
Amity University Jharkhand, Ranchi
Converting between
Strings and Lists
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Displaying only parts of a String
Amity University Jharkhand, Ranchi
Return the first few letters/numbers/characters of the string
from the left
Amity University Jharkhand, Ranchi
Return the last few letters/numbers/characters of the string
from the right
Amity University Jharkhand, Ranchi
Return a certain number of letters/numbers/characters within
the string
Amity University Jharkhand, Ranchi
Other Useful Methods
Amity University Jharkhand, Ranchi
Replace letters and words in a string
Amity University Jharkhand, Ranchi
Count how many times a character appears in a string
Or
Amity University Jharkhand, Ranchi
Find the location of a character in a string
Or
Amity University Jharkhand, Ranchi
my_string = "Python is fun“
print(my_string.replace("fun", "awesome"))
Amity University Jharkhand, Ranchi
Write a program that asks the user to enter a string. The program should then print
the following:
(a) The total number of characters in the string
(b) The string repeated 10 times
(c) The first character of the string (remember that string indices start at 0)
(d) The first three characters of the string
(e) The last three characters of the string
(f) The string backwards
(g) The seventh character of the string if the string is long enough and a message
otherwise
(h) The string with its first and last characters removed
(i) The string in all caps
(j) The string with every a replaced with an e
(k) The string with every letter replaced by a space
Amity University Jharkhand, Ranchi
Lists
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.
The list is a sequence data type which is used to store the collection of
data. Tuples and String are other types of sequence data types.
Var = ["hello", "for", "Testing"]
print(Var)
Amity University Jharkhand, Ranchi
# Creation of List
# Creating a List
List = []
print("Blank List: ") Output:
print(List)
Blank List:
# Creating a List of numbers []
List = [10, 20, 14]
print("\nList of numbers: ") List of numbers:
print(List) [10, 20, 14]
# Creating a List of strings and accessing List Items:
# using index Hello
List = ["Hello", "For", "Testing"] Testing
print("\nList Items: ")
print(List[0])
print(List[2])
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Accessing elements from a multi-dimensional list
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Similarities to strings
Amity University Jharkhand, Ranchi
L = [1,2,3]
for i in range(len(L)):
print(L[i])
for item in L:
print(item)
Output:
Amity University Jharkhand, Ranchi
Built-in functions
Amity University Jharkhand, Ranchi
Output:
Amity University Jharkhand, Ranchi
List methods
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
print([Link]())
print(List)
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Write a program that asks the user to enter a list of integers. Do the
following:
(a) Print the total number of items in the list.
(b) Print the last item in the list.
(c) Print the list in reverse order.
(d) Print Yes if the list contains a 5 and No otherwise.
(e) Print the number of fives in the list.
(f) Remove the first and last items from the list, sort the remaining
items, and print the
(g) Print how many integers in the list are less than 5.
Amity University Jharkhand, Ranchi
Lists and the random module
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Join
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Tuples in Python
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 pythonThey are as
follows:
•Using round brackets
•With one item
•Tuple Constructor
Amity University Jharkhand, Ranchi
Create Tuples using Round Brackets ()
To create a tuple we will use () operators.
var = (“hello", "for", “testing")
print(var) 1
# Get input from user
Output: input_string = input("Enter a
list of tuples: ")
(‘hello', 'for', ‘testing')
# Parse input string into list
of tuples
tuples_list =
eval(input_string)
# Print the list of tuples
print(tuples_list)
Amity University Jharkhand, Ranchi
Create a Tuple With One Item
values : tuple[int | str, ...] = (1,2,4,“Testing")
print(values)
Output:
(1, 2, 4, ‘testing)
variable called values which holds a tuple that consists of either int or str, the
‘…’ means that the tuple will hold more than one int or str.
In case your generating a tuple with a single element, make sure to add a
comma after the element. Let us see an example of the same.
Amity University Jharkhand, Ranchi
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)
Amity University Jharkhand, Ranchi
What is Immutable in Tuples?
Tuples in Python are similar to Python lists but not entirely.
Tuples are immutable and ordered and allow duplicate
values. Some Characteristics of Tuples in Python.
•We can find items in a tuple since finding any item does not
make changes in the tuple.
•One cannot add items to a tuple once it is created.
•Tuples cannot be appended or extended.
•We cannot remove items from a tuple once it is created.
Amity University Jharkhand, Ranchi
mytuple = (1, 2, 3, 4, 5)
# tuples are indexed
print(mytuple[1])
print(mytuple[4])
# tuples contain duplicate elements
mytuple = (1, 2, 3, 4, 2, 3)
print(mytuple)
# adding an element
mytuple[1] = 100
print(mytuple)
Amity University Jharkhand, Ranchi
Python Access Tuple using a Positive Index
Using square brackets we can get the values from tuples in Python.
var = (“hello", "for", “testing")
print("Value in Var[0] = ", var[0])
print("Value in Var[1] = ", var[1])
print("Value in Var[2] = ", var[2])
Output:
Value in Var[0] = hello
Value in Var[1] = for
Value in Var[2] = testing
Amity University Jharkhand, Ranchi
myList = [1, 2, 3, 4, 5]
# NORMAL INDEXING
print(myList[0])
print(myList[1])
print(myList[2])
# NEGATIVE INDEXING (STARTS FROM THE LAST ELEMENT IN THE LIST)
print(myList[-1])
print(myList[-2])
print(myList[-3])
print(myList[-3:])
1
2
3
5
4
3
[3, 4, 5]
Amity University Jharkhand, Ranchi
Different Operations Related to Tuples
Below are the different operations related to tuples in
Python:
•Concatenation
•Nesting
•Repetition
•Slicing
•Deleting
•Finding the length
•Multiple Data Types with tuples
•Conversion of lists to tuples
•Tuples in a Loop
Amity University Jharkhand, Ranchi
Concatenation of Python Tuples
# Code for concatenating 2 tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', ‘Testing')
# Concatenating above two
print(tuple1 + tuple2)
Output:
(0, 1, 2, 3, 'python', ‘Testing')
Amity University Jharkhand, Ranchi
Nesting of Python Tuples
# Code for creating nested tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', ‘Testing')
tuple3 = (tuple1, tuple2)
print(tuple3)
((0, 1, 2, 3), ('python', ‘Testing'))
Amity University Jharkhand, Ranchi
Repetition Python Tuples
We can create a tuple of multiple same elements from a single
element in that tuple.
# Code to create a tuple with repetition
tuple3 = ('python',)*3
print(tuple3)
('python', 'python', 'python')
Amity University Jharkhand, Ranchi
Slicing Tuples in Python
Slicing a Python tuple means dividing a tuple into small tuples using the
indexing method.
Amity University Jharkhand, Ranchi
Converting a List to a Tuple
(0, 1, 2)
('p', 'y', 't', 'h', 'o', 'n')
Amity University Jharkhand, Ranchi
Convert tuple into list
t1=(3,4,2,1,5,6,7)
print(t1[2:5])
t2=list(t1)
t2[3]=99
[Link]()
t3=tuple(t2)
print(t3)
Amity University Jharkhand, Ranchi
Dictionaries
A dictionary is a more general version of a list. In Python, a dictionary is mapping
between a set of indices (keys) and a set of [Link] items in a dictionary are
key-value pairs
Creating dictionaries Here is a simple dictionary:
d = {'A':100, 'B':200}
To declare a dictionary we enclose it in curly braces, {}. Each entry consists of a pair
separated by a colon. The first part of the pair is called the key and the second is the
value. The key acts like an index. So in the first pair, 'A':100, the key is 'A', the value is
100, and d['A'] gives 100. Keys are often strings, but they can be integers, floats, and
many other things as well. You can mix different types of keys in the same dictionary
and different types of values, too.
Amity University Jharkhand, Ranchi
In Python, a dictionary is mapping between a set of indices (keys) and a set of
values.
Keys can be any Python data type:
Because keys are used for indexing, they should be immutable
Values can be any Python data type:
Values can be mutable or immutable
Changing dictionaries Let’s start with this dictionary:
d = {'A':100, 'B':200}
• To change d['A'] to 400, do
d['A']=400
• To add a new entry to the dictionary, we can just assign it, like below:
d['C']=500
Note that this sort of thing does not work with lists. Doing L[2]=500 on a list with two
elements would produce an index out of range error. But it does work with dictionaries.
• To delete an entry from a dictionary, use the del operator:
del d['A']
Amity University Jharkhand, Ranchi
Empty dictionary The empty dictionary is { }, which is the dictionary equivalent of []
for lists or ‘ ' for strings.
Example 1 You can use a dictionary as an actual dictionary of definitions:
d = {'dog' : 'has a tail and goes woof!','cat' : 'says meow’, 'mouse' : 'chased by cats'}
Here is an example of the dictionary in use:
word = input('Enter a word: ')
print('The definition is:', d[word])
Enter a word: mouse
The definition is: chased by cat
Amity University Jharkhand, Ranchi
Accessing Items
You can access the items of a dictionary by referring to its key name,
inside square brackets:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
x = [Link]()
print(x)
Amity University Jharkhand, Ranchi
Copy() and Clear()
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x)
[Link]()
Print(car)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
{}
Amity University Jharkhand, Ranchi
Nested Dictionary
Output:
{'child1': {'name': 'Emil', 'year': 2004}, 'child2':
{'name': 'Tobias', 'year': 2007}, 'child3':
{'name': 'Linus', 'year': 2011}}
Amity University Jharkhand, Ranchi
Output:
{'child1': {'name': 'Emil', 'year':
2004}, 'child2': {'name': 'Tobias',
'year': 2007}, 'child3': {'name':
'Linus', 'year': 2011}}
Amity University Jharkhand, Ranchi
The list of the keys is a view of the dictionary, meaning that any
changes done to the dictionary will be reflected in the keys list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]() Output
print(x) #before the change dict_keys(['brand', 'model', 'year'])
dict_keys(['brand', 'model', 'year',
car["color"] = "white" 'color'])
print(x) #after the change
Amity University Jharkhand, Ranchi
Change Values
You can change the value of a specific item by referring to its key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
Amity University Jharkhand, Ranchi
Update Dictionary
The update() method will update the dictionary with the items from the given [Link] argument must be a
dictionary, or an iterable object with key:value pairs.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"year": 2020})
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Amity University Jharkhand, Ranchi
Adding Items
Adding an item to the dictionary is done by using a new index key and
assigning a value to it:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
Amity University Jharkhand, Ranchi
Removing Items
There are several methods to remove items from a dictionary:
The pop() method removes the item with the specified key name:
thisdict = { thisdict = {
"brand": "Ford",
"model": "Mustang",
"brand": "Ford",
"year": 1964 "model": "Mustang",
}
[Link]("model") "year": 1964
print(thisdict) }
[Link]()
print(thisdict)
{'brand': 'Ford', 'year': 1964}
Amity University Jharkhand, Ranchi
Loop in Dictionary Output:
brand
thisdict = { model
"brand": "Ford", year
"model": "Mustang",
"year": 1964 Output:
} Ford
for x in thisdict: Mustang
print(x) 1964
for x in thisdict: Output:
print(thisdict[x]) Ford
Mustang
for x in [Link](): 1964
print(x) Output:
for x, y in [Link](): brand Ford
print(x, y) model Mustang
year 1964
Amity University Jharkhand, Ranchi
Set
A Set in Python programming is an unordered collection data type that is
iterable, mutable and has no duplicate elements.
Set are represented by { } (values enclosed in curly braces)
The major advantage of using a set, as opposed to a list, is that it has a highly
optimized method for checking whether a specific element is contained in the
set. This is based on a data structure known as a hash table. Since sets are
unordered, we cannot access items using indexes as we do in lists.
Example:
var = {“Apple", “banana", “mango"}
print(var)
Amity University Jharkhand, Ranchi
Python has a set of built-in methods that you can use on sets.
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
intersection_update() Removes the items in this set that are not present in other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
Returns whether all items in this set is present in other, specified set(s)
issuperset() Returns whether this set contains another set or not
Returns whether all items in other, specified set(s) is present in this set
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
union() Return a set containing the union of sets
update() Update the set with the union of this set and others
Amity University Jharkhand, Ranchi
Add() method:
Output: {'blue', 'orange', 'red', 'green'}
Clear() method
Output: set()
Amity University Jharkhand, Ranchi
Copy() Method
Output: {'apple', 'cherry', 'banana'}
Difference() Method
Return a set that contains the items that only exist in set x, and not in
set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = [Link](y)
print(z)
Output: {'banana', 'cherry'}
Amity University Jharkhand, Ranchi
Discard Method
Remove "banana" from the set:
fruits ={"apple", "banana", "cherry"}
[Link]("banana")
print(fruits)
Output: {'apple', 'cherry'}
Intersection:
Return a set that contains the items that exist in both set x, and set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = [Link](y)
print(z)
Output: {'apple'}
Intersection_update()
Remove the items that is not present in both x and y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"} Output:{'apple'}
x.intersection_update(y)
print(x)
Amity University Jharkhand, Ranchi
Isdisjoint()
Return True if no items in set x is present in set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "facebook"}
z = [Link](y) Output: True
print(z)
Issubset()
Return True if all items in set x are present in set y:
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
z = [Link](y) Output: True
print(z)
Issuperset()
Return True if all items set y are present in set x:
x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"} Output: True
z = [Link](y)
print(z)
Pop()
Remove a random item from the set:
fruits = {"apple", "banana", "cherry"}
[Link]() Output:{'apple', 'banana'}
print(fruits)
Amity University Jharkhand, Ranchi
Remove()
Remove "banana" from the set:
fruits = {"apple", "banana", "cherry"}
[Link]("banana")
print(fruits) output:{'apple', 'cherry'}
Symmetric _difference()
Return a set that contains all items from both sets, except items
that are present in both sets:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)
Output:{'microsoft', 'google', 'banana', 'cherry'}
Amity University Jharkhand, Ranchi
Union()
Return a set that contains all items from both sets, duplicates are
excluded:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = [Link](y)
print(z)
Output: {'microsoft', 'banana', 'cherry', 'apple', 'google'}
Update()
Insert the items from set y into set x:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
[Link](y)
print(x)
Output: {'cherry', 'banana', 'google', 'apple', 'microsoft'}