Week 8 - text (strings) & data from CSV files Flashcards
How to use the index operator with strings?
[] used to index a character. Each character is a unique index.
Starts at 0
-1 looks to the last character in the string.
What does a dot.notation combine
objects with methods.
example - object.method()
How to use the slice operator with strings?
[n:m] - returns part of a string from the nth character to the mth character. However excludes the mth character (stops at the one before).
What do the “in” and “not in” operators do?
‘in’ tests if one string is a subset of another string
‘not in’ returns the logic opposite to ‘in’
What string operators also work for lists too?
indexing slicing searching (in and not in) looping concatenating
How to open a file in python?
open file = open(file_path, mode) modes: 'r' = reading a text file 'rb' = reading a binary file 'w' = writing a text file 'wb' writing a binary file
What methods are used to read a file?
variable_name.readlines(file_variable) - reads all the lines into a list
variable_name.read(file_variable) - reads whole file into one big string.
How to read CSV files
import CSV - python module that helps read compex csv files. variable_name = csv.reader(file)
How to use the CSV dictionary reader?
csv.DictReader() converts each row into a dictionary with the column header as the key.
How do you count using a looping program?
This counts a sequence of values
- Initialise a counter variable with zero before the loop
- Increment the counter in the loop (i.e. count = count + 1)
How do you sum using a looping program?
Sums a sequence of values
- Initialise a sum variable with zero before the loop.
- Add the value to the sum variable each time it loops (i.e. salary = salary + float(loop_variable[“key”])
How do you average using a looping program?
- Combine the count and sum programs
2. Then print(sum/count)
How do you accumulate data through a looping program?
Save the data to a list []
1. Initiate a variable with a blank list []
2. choose a particular colum:
a. create a variable that selects the key (top of the
program.)
b. create a variable inside the loop that selects
only the key (i.e. value = Ist_col[key]
3. Append key to list (ie. blank_list_variable.append(key_variable)