1.2.1 Data Types and Operations
1.2.1 Data Types and Operations
Slice To the End - By leaving out the start index, the range will go to
the end:
Example: Get the characters from position 2, and all the way to the
end:
b = "Hello, World!"
print(b[2:])
Output: llo, World!
Slicing strings
Negative Indexing - Use negative indexes to
start the slice from the end of the string:
Example: 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])
Output: orl
Modify Strings
• Python has a set of built-in methods that you can use on strings.
Upper Case
Example: The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
Output: HELLO, WORLD!
Lower Case
Example: The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
Output: hello, world!
Modify Strings
Remove Whitespace
• Whitespace is the space before and/or after the actual text, and very
often you want to remove this space.
• The strip() method removes any whitespace from the beginning or the
end:
Ex:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!“
Replace String
• The replace() method replaces a string with another string:
Ex:
a = "Hello, World!"
print(a.replace("H", "J")) #returns “Jello, World!”
Modify Strings
Split String
• The split() method returns a list where the text between the
specified separator becomes the list items.
• It splits the string into substrings if it finds instances of the
separator:
Example
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
String Concatenation
• To concatenate, or combine, two strings you can use the + operator.
Merge variable a with variable b into variable c:
Ex.
a = "Hello"
b = "World"
c=a+b
print(c)
Output: HelloWorld
• To add a space between them, add a " ":
Ex.
a = "Hello"
b = "World"
c=a+""+b
print(c)
Output: Hello World
String Format
• We cannot combine strings and numbers like this:
age = 36
txt = "My name is John, I am " + age
print(txt)
• This will throw an error like..
Traceback (most recent call last):
File "demo_string_format_error.py", line 2, in <module>
txt = "My name is John, I am " + age
TypeError: must be str, not int
• But we can combine strings and numbers by using the format() method.
The format() method takes the passed arguments, formats them, and
places them in the string where the placeholders {} are.
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
Output: My name is John, and I am 36
Escape Characters
• To insert characters that are illegal in a string, use an escape
character.
• An escape character is a backslash \ followed by the character
you want to insert.
• An example of an illegal character is a double quote inside a
string that is surrounded by double quotes:
Example
• You will get an error if you use double quotes inside a string that
is surrounded by double quotes:
• txt = "We are the so-called "Vikings" from the north.“
File "demo_string_escape_error.py", line 1
txt = "We are the so-called "Vikings" from the north."
^
SyntaxError: invalid syntax
Escape Characters
• To fix this problem, use the escape character \":
• Example
• The escape character allows you to use double
quotes when you normally would not be allowed:
• txt = "We are the so-called \"Vikings\" from the
north."
Other escape characters used in Python:
Code Result
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value
String Methods
Capitalize() Method
• The capitalize() method returns a string where the first
character is upper case, and the rest is lower case.
• Syntax: string.capitalize()
Upper case the first letter in this sentence:
txt = "hello, and welcome to my world."
Ex.
x = txt.capitalize()
print (x)
Output: Hello, and welcome to my world.
Ex.
txt = "python is FUN!"
x = txt.capitalize()
print (x)
Output: Python is fun!
Operation in List data type
• Access list items
• Remove List Items
• Loop Lists
• List Comprehension
• Sort Lists
• Copy Lists
• Join Lists
• List Methods
List
Access Items: List items are indexed and you can
access them by referring to the index number:
• Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1]) Output: banana
• Change a Range of Item Values: To change the value of items within a specific range,
define a list with the new values, and refer to the range of index numbers where you
want to insert the new values:
Example: Change the values "banana" and "cherry" with the values "blackcurrant" and
"watermelon":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
Output: ["apple", " blackcurrant ", " watermelon", "orange", "kiwi", "mango"]
• If you insert more items than you replace, the new items will be inserted where you
specified, and the remaining items will move accordingly:
Example: Change the second value by replacing it with two new values:
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist) Output: ["apple", " blackcurrant ", " watermelon", " cherry “]
• The length of the list will change when the number of items
inserted does not match the number of items replaced.
• If you insert less items than you replace, the new items will be
inserted where you specified, and the remaining items will move
accordingly:
• Example: Change the second and third value by replacing it
with one value:
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist) Output: ["apple", " watermelon”]
• To insert a new list item, without replacing any of the existing
values, we can use the insert() method. The insert() method
inserts an item at the specified index:
• Example: Insert "watermelon" as the third item:
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist) Output: ["apple", "banana", ”watermenlon”, "cherry"]
Add List Items
• Append Items: To add an item to the end of the list, use
the append() method:
Example: Using the append() method to append an item
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist) Output: ["apple", "banana", "cherry“, orange]
• Insert Items: To insert a list item at a specified index, use
the insert() method. The insert() method inserts an item at
the specified index:
Example: Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist) Output: ["apple", ” orange “, "banana", "cherry“]
Add List Items
• Extend List: To append elements from another list to the current list,
use the extend() method.
Example: Add the elements of tropical to thislist:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
Output: ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
The elements will be added to the end of the list.
• Add Any Iterable: The extend() method does not have to append lists,
you can add any iterable object (tuples, sets, dictionaries etc.).
Example: Add elements of a tuple to a list:
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)
Output: ['apple', 'banana', 'cherry', 'kiwi', 'orange']
Remove List Items
Remove Specified Item: The remove() method removes the
specified item.
Example: Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
Output: ["apple", "cherry"]
• If there are more than one item with the specified value,
the remove() method removes the first occurance
Example: Remove the first occurance of "banana":
thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
thislist.remove("banana")
print(thislist)
Output: ["apple", "cherry", "banana", "kiwi"]
Remove Specified Index: The pop() method removes
the specified index.
Example: Remove the second item:
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
Output: ["apple", "cherry"]
If you do not specify the index, the pop() method
removes the last item.
• Example: Remove the last item:
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist) output: [‘apple’, ‘banana’]
• The del keyword also removes the specified index
Example: Remove the first item:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
Output: ["banana", "cherry"]
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.
1. Convert into a list: Just like the workaround
for changing a tuple, you can convert it into a list,
add your item(s), and convert it back into a tuple.
Example: Convert the tuple into a list, add
"orange", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
2. Add tuple to a tuple. You are allowed to
add tuples to tuples, so if you want to add one
item, (or many), create a new tuple with the
item(s), and add it to the existing tuple:
Example: Create a new tuple with the value
"orange", and add that tuple:
thistuple =
("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
Unpack Tuples
• When we create a tuple, we normally assign values to
it. This is called "packing" a tuple:
• Example: Packing a tuple:
fruits = ("apple", "banana", "cherry")
print(green)
print(tropic)
print(red)
Loop Tuples
• Loop Through a Tuple
Iterate through the items and print the values:
thistuple =
("apple", "banana", "cherry")
for x in thistuple:
print(x)
• Loop Through the Index Numbers
You can also loop through the tuple items by
referring to their index number.
Use the range() and len() functions to
create a suitable iterable.
• Print all items by referring to their
index number:
• thistuple =
("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])
Using a While Loop
You can loop through the tuple items by using
a while loop.
Use the len() function to determine the length of the
tuple, then start at 0 and loop your way through the
tuple items by referring to their indexes.
Remember to increase the index by 1 after each
iteration.
Print all items, using a while loop to go through
all the index numbers:
thistuple = ("apple", "banana", "cherry")
i = 0
while i < len(thistuple):
print(thistuple[i])
i = i + 1
Join Two Tuples
To join two or more tuples you can use the + operator:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Syntax
tuple.count(value)
Output:
Apple
Banana
Cherry
Check if "banana" is present in the set:
• thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
• Once a set is created, you cannot change its items,
but you can add new items.
Add Set Items
del thisset
print(thisset)
Loop Sets
• You can loop through the set items by using
a for loop:
Output:
apple
banana
cherry
Join sets
• Join Two Sets: there are several ways to join two or more sets in
Python. You can use the union() method that returns a new
set containing all items from both sets, or update() method
that inserts all the items from one set into another
• The union() method returns a new set with all items from both
sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3) Output: {1, 'c', 'a', 2, 3, 'b'}
z = x.symmetric_difference(y)
x = car.keys()
car["color"] = "white"
The list of the values is a view of the dictionary, meaning that any
changes done to the dictionary will be reflected in the values list.
Example
Update the "year" of the car by using
the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
Removing Items
There are several methods to remove items from a dictionary:
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
The popitem() method removes the last inserted item (in versions
before 3.7, a random item is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
Access Items in Nested Dictionaries