UNIT 3
Strings
Definition & Accessing :
Like many other popular programming languages, strings in Python are arrays of bytes
representing Unicode characters.
However, Python does not have a character data type, a single character is simply a string with a
length of 1.
Square brackets can be used to access elements of the string.
Ex:
a = "Hello, World!"
print(a[1])
Since strings are arrays, we can loop through the characters in a string, with a for loop.
Ex:
for x in "banana":
print(x)
The len() function returns the length of a string:
Ex: a = "Hello, World!"
print(len(a))
Check if "free" is present in the following text using “in”:
Ex: txt = "The best things in life are free!"
print("free" in txt)
To concatenate, or combine, two strings you can use the + operator.
Ex:
a = "Hello"
b = "World"
c=a+b
print(c)
** we can not concatenate numbers to strings as show below:
age = 36
txt = "My name is John, I am " + age
print(txt)
** it raises error.
** in python the functions defined in a class are called methods and that are defined outside class
(directly with in python runtime environment) are called functions. So the functions are called
directly (without object) and the methods are called with an object.
These are list of methods of string class.
capitalize() Converts the first character to upper case
count() Returns the number of times a specified value occurs in a string
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of
where it was found
index() Searches the string for a specified value and returns the position of
where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isspace() Returns True if all characters in the string are whitespaces
isupper() Returns True if all characters in the string are upper case
lower() Converts a string into lower case
replace() Returns a string where a specified value is replaced with a specified
value
split() Splits the string at specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
upper() Converts a string into upper case
slicing and basic operations :
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):
b = "Hello, World!"
print(b[-5:-2])
---
Q. Write about strings in python
---
Lists
Introduction:
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:
thislist = ["apple", "banana", "cherry"]
print(thislist)
accessing list:
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
Lists are ordered, it means that the items have a defined order, and that order will not change. If
you add new items to a list, the new items will be placed at the end of the list. So these maintain
the order in which the data is stored in it. The list is changeable, meaning that we can change,
add, and remove items in a list after it has been created.
Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
we can store different data type elements in a list like strings, integers and boolean values:
list1 = ["abc", 34, True, 40, "male"]
* we can also use the list() constructor to make a List, but it takes only one argument.
thislist = list(("apple", "banana", "cherry"))
OR
thislist = list(["apple", "banana", "cherry"])
but….writing as below is WRONG.
thislist = list("apple", "banana", "cherry"), as there are three string arguments.
we can loop through the lists in 2 ways:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
OR
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
we can also sort lists with the functions of List class :
sorting ascending order (by default)
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
sorting in descending order:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
we can join lists in 3 ways :
1. list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
2. list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
3. list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
Operations :
We can add items to list, modify data in a list and remove items in a list.
Modifying items :
We can change items in a list
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
we can also change multiple values as shown below:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
adding items to a list :
we can Use the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
we can also insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
removing items in a list:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
thislist = ["apple", "banana", "cherry"]
del thislist
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the lis
---
Q. Explain about lists in python
---
Tuples
introduction, accessing tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
Ex:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Tuple items are ordered, unchangeable, and allow duplicate values. Tuple items are indexed, the
first item has index [0], the second item has index [1] etc. tuples are ordered, it means that the
items have a defined order, and that order will not change. Tuples are unchangeable, meaning
that we cannot change, add or remove items after the tuple has been created.
thistuple = ("apple",) this is treated as a tuple object, and a tuple must have more than one
element.
thistuple = ("apple"), this is treated as a string object and NOT as tuple as it has only one
element.
we can unpack tuple into variables as individual values:
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
now, there are three variables created with names green, yellow and red and stored with the
values of the tuple “apple”,”banana” and “cherry”.
Looping through the tuple is also similar to looping through lists :
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])
or
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
as tuples are not modifiable, if we get a requirement of modifying values of a tuple, we can store
tuple into a list, do modification in that list and then store values back into the tuple as shown
below:
fruits = ("apple", "banana", "cherry")
print('before modification', fruits)
test=list(fruits)
test[1]='tested value'
fruits=tuple(test)
print('after modification',fruits)
---
Q. explain tuples in python
---
Dictionaries
introduction, accessing values in dictionaries
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered, changeable and do not allow duplicates. In python,
in old versions the dictionaries were un-ordered. Dictionaries are written with curly brackets, and
have keys and values.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
output :
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
** in lists or tuples, we use index number to refer each item. But in dictionaries, we use key to
refer each item instead of index number.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Dictionaries cannot have two items with the same key:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
** Duplicate values will overwrite existing values.
Getting values can be done in different ways:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
OR
x = thisdict.get("model")
to get all the keys in dictionary:
x = thisdict.keys()
to get all the values in dictionary :
x = thisdict.values()
we can change values or dictionaries as show below:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
we can add items DYNAMICALLY as shown below in 2 way :
1. either by setting we value to new key
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
2. or by using update function
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
we can use del, pop(), popitem(), clear() to remove items of the dictionary as we can do with
tuples.
Looping is done in different ways :
for x in thisdict:
print(x)
for x in thisdict:
print(thisdict[x])
for x in thisdict.values():
print(x)
for x in thisdict.keys():
print(x)
for x, y in thisdict.items():
print(x, y)
---
Q. write about dictionaries of python
---