cs 105
play

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,


  1. CS 105 Lecture 8: Strings and Files Craig Zilles (Computer Science) https://go.illinois.edu/cs105sp20 March 22, 2020

  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

  3. Sl Slici cing • For string slicing the main part that confuses me is counting spaces • how do negative numbers work when slicing? Number of Characters Type characters (Stored using Unicode encoding) ‘CS 105’ String 6 001000011 001010011 000100000 000110001 000110000 000110101 C S 1 0 5 my_str = "CS 105" print(my_str[:3]) print(my_str[2:]) print(my_str[1:4]) 3

  4. Sl Slici cing Number of Characters Type characters (Stored using Unicode encoding) ‘CS 105’ String 6 001000011 001010011 000100000 000110001 000110000 000110101 C S 1 0 5 my_str = "CS 105" print(my_str[-4:-2]) A) 'S 1' B) 'S 10' C) ' 1' D) ' 10' E) None of these 4

  5. Sl Slici cing ou out s speci cific r c region ons • Example: Remove all parenthesized regions from a string • "This string (foo) has (bar) things" 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 5

  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

  7. St Stri ring j joi oining • The opposite of splitting • Pretty common pattern: mylist = input .split( separator ) … process mylist … output = separator .join( mylist ) output = ','.join(input.split(',')[::2]) 7

  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

  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

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

  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 one page at a time whole file at once cat 11

  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

  13. Wr Writing to files • file_object = open('filename', 'w') • file_object.write('thing to write') • file_object.close() automatic at program end optional • file_object.flush() Example program 1: Diary that records user input into a file. with open('filename', 'w') as outf: closes file when code block ends 13

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

  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

  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

  17. Cr Create a list of of Illinoi ois U.S. representatives 17

  18. Re Reading fro rom files • file_object = open('filename') • lines = file_object.readlines() • for line in lines: 18

  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

  20. Fi Filter ering a a collec ection (patter ern) newlist = [] for thing in collection : if thing meets criteria : newlist .append( thing ) 20

Recommend


More recommend