Module 4
Module 4
Strings
Strings in python are surrounded by either single quotation marks, or double quotation
marks.
'hello' is the same as "hello".
Example
print("Hello")
print('Hello')
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.
Example
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the
keyword not in.
Example
Check if "expensive" is NOT present in the following text:
txt = "The best things in life are free!"
print("expensive" not in txt)
Lower Case
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
Remove Whitespace
Whitespace is the space before and/or after the actual text, and very often you want to
remove this space.
Example
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
Replace String
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
Split String
The split() method returns a list where the text between the specified separator becomes the list
items.
Example
The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
Python - String Methods
Python Lists
• 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:
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
List Items
• 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.
Ordered
• When we say that 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.
Changeable
The list is changeable, meaning that we can change, add, and remove items
in a list after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
Example
Python Tuples
• 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.
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Tuple Items
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.
Ordered
When we say that tuples are ordered, it means that the items have a defined order, and that order
will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has
been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
print(x)
Add Items
Since tuples are immutable, they do not have a built-in append() method, but there are
other ways to add items to a tuple.
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
Remove Items
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
Method Description
index() Searches the tuple for a specified value and returns the position of where it
was found
Dictionary
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.
Dictionaries are a useful data structure for storing data in Python because they are
capable of imitating real-world data arrangements where a certain value exists for a
given key.
The data is stored as key-value pairs using a Python dictionary.
o This data structure is mutable
o The components of dictionary were made using keys and values.
o Keys must only have one component.
o Values can be of any type, including integer, list, and tuple.
A dictionary is, in other words, a group of key-value pairs, where the values can be any
Python object. The keys, in contrast, are immutable Python objects, such as strings, tuples,
or numbers. Dictionary entries are ordered as of Python version 3.7. In Python 3.6 and
before, dictionaries are generally unordered.
Dictionary Items
Dictionary items are ordered, changeable, and do not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Ordered or Unordered?
When we say that dictionaries are ordered, it means that the items have a defined
order, and that order will not change.
Unordered means that the items do not have a defined order, you cannot refer to an
item by using an index.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
type()
From Python's perspective, dictionaries are defined as objects with the data type
'dict':
<class 'dict'>
Example
Print the data type of a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))
Change Values
You can change the value of a specific item by referring to its key name:
Example
Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
Update Dictionary
The update() method will update the dictionary with the items from the given argument.
The argument must be a dictionary, or an iterable object with key:value pairs.
Example
Update the "year" of the car by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
print(union_set)
2. Set Intersection
The intersection of two sets is the set that contains all of the common elements of both sets.
To find the intersection of two Python sets, we can either use the intersection() method or &
operator.
Here is an example to demonstrate this.
• Python
set1 = {11, 22, 33}
set2 = {33, 54, 75}
# Perform intersection operation using the `&` operator or the `intersection()` method
intersection_set = set1 & set2
# Or: intersection_set = set1.intersection(set2)
print(intersection_set)
3. Set Difference
The difference between the two sets is the set of all the elements in the first set that are not
present in the second set. To accomplish this, we can either use the difference() function or
the – operator in python.
Here is an example to demonstrate this.
• Python
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
set3 = set1.difference(set2)
print(set3)
set4 = set1 - set2
print(set4)
Issubset
The issubset() operation is used in Python to check whether a set is a subset of another set.
Here’s an example to demonstrate this:
• Python
set1 = {1, 2, 3, 4, 5}
set2 = {2, 4}
print(set2.issubset(set1))
print(set1.issubset(set2))
Isdisjoint
The isdisjoint() operation in Python is used to check whether two sets have any common
elements. If the two sets have no common elements, then they are said to be disjoint.
Here’s an example to demonstrate this:
• Python
set1 = {1, 2, 3, 4, 5}
set2 = {6, 7, 8}
print(set1.isdisjoint(set2))
set3 = {4, 5, 6}
set4 = {6, 7, 8}
print(set3.isdisjoint(set4))