CS 105 Lecture 8: Strings and Files Craig Zilles (Computer Science) - - PowerPoint PPT Presentation

cs 105
SMART_READER_LITE
LIVE PREVIEW

CS 105 Lecture 8: Strings and Files Craig Zilles (Computer Science) - - PowerPoint PPT Presentation

CS 105 Lecture 8: Strings and Files Craig Zilles (Computer Science) https://go.illinois.edu/cs105sp20 March 22, 2020 To Today 1. Slicing 2. Splitting and Joining 3. String Formatting (redux) 4. Files Extensions, Writing, flushing,


slide-1
SLIDE 1

Lecture 8: Strings and Files

Craig Zilles (Computer Science) March 22, 2020 https://go.illinois.edu/cs105sp20

CS 105

slide-2
SLIDE 2

To Today

  • 1. Slicing
  • 2. Splitting and Joining
  • 3. String Formatting (redux)
  • 4. Files
  • Extensions,
  • Writing, flushing, closing
  • 5. Comma-separated values (CSV) files
  • Reading, splitting & filter

2

slide-3
SLIDE 3

Sl Slici cing

  • For string slicing the main part that confuses me is

counting spaces

  • how do negative numbers work when slicing?

my_str = "CS 105" print(my_str[:3]) print(my_str[2:]) print(my_str[1:4])

3

String 6 001000011 001010011

Type Number of characters Characters (Stored using Unicode encoding)

000100000 000110001 000110000 000110101 ‘CS 105’ C S 1 5

slide-4
SLIDE 4

Sl Slici cing

my_str = "CS 105" print(my_str[-4:-2]) A) 'S 1' B) 'S 10' C) ' 1' D) ' 10' E) None of these

4

String 6 001000011 001010011

Type Number of characters Characters (Stored using Unicode encoding)

000100000 000110001 000110000 000110101 ‘CS 105’ C S 1 5

slide-5
SLIDE 5

Sl Slici cing ou

  • ut s

speci cific r c region

  • ns
  • Example: Remove all parenthesized regions from a string
  • "This string (foo) has (bar) things"

def remove_parentheticals(string): while '(' in string:

  • pen_index = string.find('(')

close_index = string.find(')') string = string[:open_index] + string[close_index + 2:] return string

5

slide-6
SLIDE 6

St Stri ring s splitting

  • I really do not know how the separators will perform and

why; that is, what will be the result of the split() confuses me a lot.

  • Will the split function always return a list or are there

exceptions?

  • String splitting is when you have a string w/separators
  • Normal sentences using whitespace
  • "This is a sentence.".split()
  • Comma separate variables
  • "1, 2, 3, 4".split(', ')

6

slide-7
SLIDE 7

St Stri ring j joi

  • ining
  • The opposite of splitting
  • Pretty common pattern:

mylist = input.split(separator) … process mylist …

  • utput = separator.join(mylist)
  • utput = ','.join(input.split(',')[::2])

7

slide-8
SLIDE 8

Py Python Format at Strings

  • a_string.format(parameters)
  • "a {} way".format("better")
  • "can {1} the {0}".format("order",

"control")

  • "precision {0:.2f}".format(math.pi)

8

slide-9
SLIDE 9

Fo Format string va variable formatting

  • "{0:05.2f}".format(a))

# num digits

  • '{:<30}'.format(a)

# < > ^

  • '{:.^30}'.format(a)

# fill with chars

  • '{:,}'.format(1234567890) # commas

9

slide-10
SLIDE 10

Fi Files es

  • Files are how data is stored on external storage (disk)
  • Managed by O/S
  • Disk is slow
  • opening files moves them to memory for the program
  • Data is buffered (temporarily stored) in memory

10

slide-11
SLIDE 11

Vi Viewi wing ng the he fi files esystem em

  • Mac Finder / Windows explorer
  • Command line:
  • Mac:

ls ls -l

  • Windows:

dir

  • Shows all of the files in the current directory
  • Can show file size
  • Looking at files (Mac): more
  • ne page at a time

cat whole file at once

11

slide-12
SLIDE 12

Wr Write programs a few lines at a tim time! Te Test every couple lines to make sur sure the hey y do do wha hat you u want!

12

slide-13
SLIDE 13

Wr Writing to files

  • file_object = open('filename', 'w')
  • file_object.write('thing to write')
  • file_object.close() automatic at program end
  • file_object.flush()
  • ptional

Example program 1: Diary that records user input into a file. with open('filename', 'w') as outf: closes file when code block ends

13

slide-14
SLIDE 14

Di Diary tha hat records ds us user input nput into a file.

14

slide-15
SLIDE 15

Co Continue wr writing to existing file? (i (i.e., new writes go to end of f fi file)

A) open('filename', 'r') B) open('filename', 'x') C) open('filename', 'i') D) open('filename', 'a') E) open('filename', 'e')

15

slide-16
SLIDE 16

Com Comma-se sepa parated d value ue (C (CSV) V) fi files

  • Commonly-used data file format
  • Can be generated from Excel and other spreadsheets

Processing a CSV manually:

  • Each row is its own line of the file
  • Can use split(',') to separate the columns
  • Use indexing to read columns of interest

Example program 2: Create a list of Illinois U.S. representatives

16

slide-17
SLIDE 17

Cr Create a list of

  • f Illinoi
  • is U.S. representatives

17

slide-18
SLIDE 18

Re Reading fro rom files

  • file_object = open('filename')
  • lines = file_object.readlines()
  • for line in lines:

18

slide-19
SLIDE 19

Sk Skipping f first l line

A) for line in lines[:1]: B) for line in lines[1:]: C) for line in lines[:2]: D) for line in lines[2]: E) for line in lines[2:]:

19

slide-20
SLIDE 20

Fi Filter ering a a collec ection (patter ern)

newlist = [] for thing in collection: if thing meets criteria: newlist.append(thing)

20