CS 105: TOPIC 8 – STRINGS AND FILES TOPIC 9…ISN'T IN THIS Max Fowler (Computer Science) https://pages.github-dev.cs.illinois.edu/cs-105/web/ JULY 5, 2020
Week 5 Video Series Topics String operations Slicing Splitting, joining Files Writing, flushing, closing Comma-separated values (CSV files) Reading, splitting, filter Coding patterns – how to recognize and apply common idioms
String ops – slicing
String slicing Slicing is how we "slice" out a part of a collection as a copy Given…
Slicing my_str = "CS105" print("_{}_".format(my_str[:3])) _CS _ 1. 1. Note the white space! print("_{}_".format(my_str[2:]) 2. _ 105_ 2. print("_{}_".format(my_str[1:4])) 3. _S 1_ 3.
What about a whole slice? my_str = "Hello" my_str_2 = my_str[:] Copies the string More important for lists later on…
What about negative slices for "CS 105"? print("_{}_".format(my_str[-4:-1])) Prints: _ 10_ How? -4 -> 4 spots back from the end of the string -1 -> 1 spot back from the end of the string
Slicing out specific regions Remove parenthesized regions from a string def remove_parentheticals(string): while '(' in string: open_index = string.find('(') close_index = string.find(')') string = string[:open_index] + string[close_index + 2:] return string
Video question What is the slice provided when I use the following code? a_str = "This is an uninspired sample string." print(a_str[a.find('a'):]
String ops – Split and Join
What is split? split separates a string into a list, based on a separator. "I want all the words in this sentence".split() #The default is whitespace, so we'd get ["I", "want", "all", "the", "words", "in", "this", "sentence"] A very common separator is the comma – comma separated variables! "1,2,3,4".split(",")
Joining Joining is the opposite of splitting! Fairly common pattern – split, process, rejoin mylist = input.split(separator) do some processing output = separator.join(mylist)
For example… Given a string of comma separated numbers… Add two to each number and return a comma separated string! How can we do this? A split, a loop, and a join!
Video question What list do I get when I use the following split? "This is a sample!".split("s")
Files
Files Files are how data is stored on external storage/the "disk" Operating system manages the files Disk is slow open moves files to memory in a temporary buffer (temp storage)
File operation - writing file_object = open('filename', 'w') file_object.write('thing to write') file_object.close() automatic at program end file_object.flush() optional
Or, use a with block Will automatically close the file at the end! with open('filename', 'w') as outf: write stuff to outf #File is closed at this scope other code…
Sample program - Write a shopping list to a file…
Video question Opening a file moves the file temporarily from where to where?
CSV Files and File Reading
Comma-separated value (CSV) files Very common data format Can be generated from spreadsheet programs – or Python! To process… Each "row" is a line in the file split(',') can separate columns Indexing reads columns of interest
Opening in general file_object = open('filename') lines = file_object.readlines() for line in lines: do things
Let's take a sample CSV I have a CSV of names and car makes/brands I want to count how many times each brand shows up!
Video Question Which of these will skip the first line in a file after reading the lines in? for line in lines[1:]: for line in lines[:1]: for line in lines[1]: for line in lines[2:]:
Common Coding Patterns
Coding… Coding is a lot like building a birdhouse Recognize task -> use a pattern from your toolkit Use a hammer and nails to fix the roof to a birdhouse… Use a for loop to process a list…
Common Idioms Check if even/odd Visit everything in a collection Sum Counter Finding "best" in collection Filtering a collection
Check if something is even/odd ( value % 2) == 0 # returns True if value is even ( value % 2) != 0 # returns True if value is odd ( value % 2) == 1 # returns True if value is odd
Visit everything in a collection for thing in collection : … thing …
Computing a sum / total total = 0 # initialize variable to zero … # usually in a loop total += value # accumulate … total … # do something with the total Also Average = sum / count
Counting counter = 0 # initialize variable to zero … # usually in a loop and/or conditional counter += 1 # increment … counter … # do something with the counter
Finding best in a collection current_best = a value you know is worse than best for thing in collection : if thing is better than current_best : current_best = thing return / do something with current_best
Filtering a collection (pattern) newlist = [] for thing in collection : if thing meets criteria : newlist .append( thing )
Compose patterns to solve problems Write a function that counts the number of even elements in a list… What patterns are needed here? Even/odd check pattern Filtering pattern
Video question You are asked to count how many strings in a list have the longest length in the list – for example… ["zebra", "bob", "cobra", "fish", "a"] would have a count of 2 – zebra and cobra are the longest strings What two patterns could you combine for this task?
Recommend
More recommend