Part 5
-
Working With Strings
Part 1
-
What Is It?
A string is an immutable sequence of characters.
name = 'Marklar'
print(name)
# 'Marklar'
-
Index Of A String
An index is an offset from the beginning of a sequence.
name = 'Marklar'
first_letter = name[0]
print(first_letter)
# 'M'
second_letter = name[1]
print(second_letter)
# 'a'
-
Expressions Are Allowed
You can use an expression that contains variables and operators to describe the index.
i = 0
name = "Guido"
print(name[i])
# G
print(name[i + 1])
# u
-
But…
The value of the index has to be an integer.
>>> print(name[2.2])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers, not float
-
The len Built-in Function
Len is a built-in function that returns the length of an object. When the argument passed to it is a string, it returns the number of characters in the string.
len('one')
# 3
len('four')
# 4
-
The Last Item
typing = "Duck"
print(len(typing))
# 4
last_char = typing[len(typing) - 1]
print(last_char)
# k
Or we can use negative indices
print(typing[-1])
# k
print(typing[-2])
# c
-
Working With Strings
Part 2
-
While Loop
index = 0
word = 'python'
while index < len(word):
letter = word[index]
print(letter)
index = index + 1
# p
# y
# t
# h
# o
# n
-
For Loop
word = 'python'
for letter in word:
print(letter)
# p
# y
# t
# h
# o
# n
-
String Slices
A slice is a segment of a sequence.
full_name = 'Guido van Rossum'
print(full_name)
# Guido van Rossum
first_name = full_name[:5]
print(first_name)
# Guido
last_name = full_name[6:]
print(last_name)
# van Rossum
print(full_name[5:6])
# ' '
-
String Slices - Negative Values
mind_trick = "These aren't the droids you're looking for"
mind_trick[-11:]
# 'looking for'
mind_trick[:-19]
# "These aren't the droids"
mind_trick[13:-19]
# 'the droids'
-
Extended Slices
semordnilap = "stressed"
semordnilap[::-1] # Reverse the string
# 'desserts'
skippy = "Mississippi"
skippy[::2] # Skip every other letter
# ''Msispi''
-
Strings Are Immutable
a = 'top'
a[0] = 'p'
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: 'str' object does not support item assignment
-
Working With Strings
Part 3
-
String Methods - upper
fruit = 'banana'
upper_banana = fruit.upper()
print(upper_banana)
# BANANA
-
String Methods - lower
fruit = 'BANANA'
lower_banana = fruit.lower()
print(lower_banana)
# banana
-
String Methods - replace
fruit = 'BANANA'
funny_banana = fruit.replace("N", "H")
print(funny_banana)
# BAHAHA
-
String Methods - find
The find method returns the lowest index in the string where substring is found within the slice. If substring is not found, the method returns -1.
fruit = 'apple'
fruit.find('p')
# 1
fruit.find('i')
# -1
-
Docs On Strings
-
Lists
Part 1
-
What Is It?
A list is a sequence of values.
Lists are mutable.
Items in a list can be any type.
-
Creating A List
- comma separated list of values enclosed in square brackets
- using the built-in list() function
-
Using Square Brackets
vowels = ['a', 'e', 'i', 'o', 'u']
pets = ['DOG', 'CAT', 'BIRD']
nums = [1, 7, 14, 21, 28]
-
List Function
make = 'Yamaha'
make_items = list(make)
print(make_items)
# ['Y', 'a', 'm', 'a', 'h', 'a']
-
Elements Don’t have to be The Same Type
random_stuff = [1, 'DOG', True, 2.3]
-
Lists Can Contain (Nested) Lists
more_random_stuff = [1, 'DOG', ['BALL', 'BAT']]
-
Accessing Elements From A List
Elements can be accessed with square brackets [].
Sequences are 0-indexed.
vowels = ['a', 'e', 'i', 'o', 'u']
vowels[0]
# 'a'
-
Accessing Elements From A Nested List
stuff = [1, 'DOG', ['BALL', 'BAT']]
stuff[0]
# 1
stuff[2]
# ['BALL', 'BAT']
stuff[2][0]
# 'BALL'
stuff[2][1]
# 'BAT'
-
Lists Are Mutable
pets = ['DOG', 'CAT', 'BIRD']
pets[1] = 'TURTLE'
print(pets)
# ['DOG', 'TURTLE', 'BIRD']
-
Lists
Part 2
-
Traversing A List
people = ['Joe', 'Jessica', 'James', 'Jennifer']
for person in people:
print(person)
# Joe
# Jessica
# James
# Jennifer
-
List Operations
Operator | Operation |
---|---|
+ | List Concatenation |
* | List Repetition |
in | Element is a member of the sequence |
not (in) | Element is not a member of the sequence |
-
List Concatenation
parts_a = ['wheels', 'handlebar', 'tank']
parts_b = ['frame', 'chain', 'engine']
parts_c = parts_a + parts_b
print(parts_c)
# ['wheels', 'handlebar', 'tank', 'frame', 'chain', 'engine']
-
List Repetition
noise = ['Honk']
noise * 3
# ['Honk', 'Honk', 'Honk']
percolate = ["It's", "Time", "For", "The", "Percolator"]
percolate * 3
# ["It's", 'Time', 'For', 'The', 'Percolator', "It's", 'Time', 'For', 'The', 'Percolator', "It's", 'Time', 'For', 'The', 'Percolator']
-
Membership Operators
marvel_heroes = ['Ironman', 'Thor', 'Black Panther', 'Black Widow']
'Batman' in marvel_heroes
# False
'Batman' not in marvel_heroes
# True
-
List Slices
A slice is a segment of a sequence.
colors = ['r', 'o', 'y', 'g', 'b', 'i', 'v']
first_three = colors[:3]
print(first_three)
# ['r', 'o', 'y']
last_four = colors[3:7]
print(last_four)
# ['g', 'b', 'i', 'v']
-
Assignment With Slices
values = [1, 2, 3, 4, 5, 6]
values[1:4] = ['a', 'b', 'c']
print(values)
# [1, 'a', 'b', 'c', 5, 6]
-
Lists
Part 3
-
List Methods - append
Add new element to the end of a list.
letters = ['a', 'b', 'c']
letters
# ['a', 'b', 'c']
letters.append('d')
print(letters)
# ['a', 'b', 'c', 'd']
-
List Methods - insert
Add a new element to a specific location.
This operation is computationally expensive and should be avoided.
letters = ['a', 'b', 'c']
letters
# ['a', 'b', 'c']
letters.insert(2, 'what am i even doing with these letters?')
letters
# ['a', 'b', 'what am i even doing with these letters?', 'c']
-
List Methods - extend
Append all elements of a list argument to another list
t1 = ['a', 'b', 'c']
t2 = ['d', 'e']
t1.extend(t2)
print(t1)
# ['a', 'b', 'c', 'd', 'e']
print(t2)
# ['d', 'e']
-
List Methods - sum
Add up elements of a list.
grades = [60, 70, 90]
average = sum(grades) / len(grades)
print(average)
# 73.33333333333333
-
List methods - sort
The sort method will modify the list so that the items are sorted.
customer_age = [53, 18, 35, 33, 20, 30]
customer_age.sort()
customer_age
# [18, 20, 30, 33, 35, 53]
The sorted built in function will return a new sorted list without modifying the existing list.
customer_age = [53, 18, 35, 33, 20, 30]
sorted_customers = sorted(customer_age)
customer_age
# [53, 18, 35, 33, 20, 30]
sorted_customers
# [18, 20, 30, 33, 35, 53]
-
Lambdas Revisited
From the docs…
Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.
students = [
['john', 'A', 15],
['jane', 'B', 12],
['dave', 'B', 10],
]
students
# [['john', 'A', 15], ['jane', 'B', 12], ['dave', 'B', 10]]
students.sort(key=lambda student: student[2])
students
# [['dave', 'B', 10], ['jane', 'B', 12], ['john', 'A', 15]]
-
Lists
Part 4
-
Deleting Elements
- pop
- del
- remove
-
pop
Uses an index to remove an element from the list.
Returns the removed element.
If no index is provided, it will default to the last element.
nums = [1, 2, 3]
print(nums)
# [1, 2, 3]
x = nums.pop(2)
print(x)
# 3
print(nums)
# [1, 2]
y = nums.pop()
print(y)
# 2
print(nums)
# [1]
-
del
Same as pop but does not return the removed value.
nums = [1, 2, 3]
del nums[2]
print(nums)
# [1, 2]
-
remove
Remove an item by the value rather than by index. Returns None.
fruits = ['apples', 'bananas', 'peaches']
val = fruits.remove('bananas')
print(val)
#None
print(fruits)
# ['apples', 'peaches']
-