Pythonmod4 Shirin
Pythonmod4 Shirin
Strings
Strings in python are surrounded by either single quotation marks, or double
quotation marks.
Example
print('Hello')
output:
Hello
Hello
Example
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
It's alright
He is called 'Johnny'
He is called "Johnny"
Example
a = "Hello"
print(a)
output:
Hello
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Note: in the result, the line breaks are inserted at the same position as in the
code.
However, Python does not have a character data type, a single character is
simply a string with a length of 1.
Example
Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
output:
e
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
output:
b
a
n
a
n
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))
output:
13
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)
output:
true
Use it in an if statement:
Example
Print only if "free" is present:
output:
Yes, 'free' is present.
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:
output:
true.
Use it in an if statement:
Example
print only if "expensive" is NOT present:
output:
Specify the start index and the end index, separated by a colon, to return a
part of the string.
Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
output:
llo
Example
b = "Hello, World!"
print(b[:5])
output:
Hello
Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
output:
llo, World!
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())
HELLO, WORLD!
Lower Case
Example
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
hello, world!
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:
Hello,World!
Replace String
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
Jello, World!
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!']
String Methods
Python has a set of built-in methods that you can use on strings.
Note: All string methods return new values. They do not change the original
string.
Method Description
List
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.
Example
Create a List:
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.
Note: There are some list methods that will change the order, but in general:
the order of the items will not change.
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:
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
Example
String, int and boolean data types:
Example
A list with strings, integers and boolean values:
type()
From Python's perspective, lists are defined as objects with the data type
'list':
<class 'list'>
Example
What is the data type of a list?
Example
Using the list() constructor to make a List:
Access Items
List items are indexed and you can access them by referring to the index
number:
banana
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the list:
cherry
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 list with the specified
items.
Example
Return the third, fourth, and fifth item:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Example
Change the second item:
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)
Append Items
To add an item to the end of the list, use the append() method:
Insert Items
To insert a list item at a specified index, use the insert() method.
Example
Insert an item as the second position:
Extend List
To append elements from another list to the current list, use
the extend() method.
Example
Add the elements of tropical to thislist:
Example
Add elements of a tuple to a list:
Example
Remove "banana":
['apple', 'cherry']
If there are more than one item with the specified value,
the remove() method removes the first occurrence:
Example
Remove the first occurrence of "banana":
Example
Remove the second item:
['apple', 'cherry']
If you do not specify the index, the pop() method removes the last item.
Example
Remove the last item:
['apple', 'banana']
Example
Remove the first item:
['banana', 'cherry']