Download presentation
Presentation is loading. Please wait.
1
Strings, Lists, and Files
Professor Hugh C. Lauer CS-1004 — Introduction to Programming for Non-Majors (Slides include materials from Python Programming: An Introduction to Computer Science, 2nd edition, by John Zelle and copyright notes by Prof. George Heineman of Worcester Polytechnic Institute) CS-1004, A-Term 2014 Strings, Lists, and Files
2
Reading Assignment Chapter 5:– Sequences
I.e., Strings, Lists, and Files CS-2301, D-Term 2014 Introduction
3
What is a String? String literal:–
Any piece of text enclosed in matching quotes May be single or double quotes “This sentence, of course, is written in English.” ‘Esta frase se escrita en español.’ ‘Wir können auch in Deutsch und Französisch zu schreiben‘ “En fait, nous pouvons écrire les chaînes en Python en japonais, aussi.” ‘Pythonはあっても、私たちは日本語などのアジアの言語で書くことができます。’ Anything that you can type in ANY language can be represented and stored as a string in Python! Unicode standard CS-2301, D-Term 2014 Introduction
4
String literal (continued)
A string literal is a constant, … … just like a numerical value Example:– S = 'This is a string!' The name S refers to the value ‘This is a string!’ Without the quotes Quotes must be paired Either single or double CS-2301, D-Term 2014 Introduction
5
Operations on Strings + — concatenation * — repetition [] — indexing
S = "This is a string" T = "and this is a another string" U = S + ', ' + T + '.' What is the value of U? * — repetition Y = "yuck, yuckity, " Y * 5 [] — indexing Like lists S[0] T[1] U[2] U[-1] U[-2] CS-2301, D-Term 2014 Introduction
6
Operations on Strings (continued)
Slicing I.e., taking a subset of a string S = "This is a string" T = S[5:7] Special cases U1 = S[-7:-1] U2 = S[-7:] U3 = S[:-7] ... Starting position of substring End of substring — This character is not included CS-2301, D-Term 2014 Introduction
7
Operations on Strings (continued again)
len(S) — length of string in characters for c in S: Iterate thru the characters of the string S ord('c') Get the Unicode character number of c 'c' must be a string of length 1 chr(int) Return a string containing a single character, the ord of which is int CS-2301, D-Term 2014 Introduction
8
Useful string methods s.capitalize() s.count(sub) s.find(sub)
Count occurrences of a substring s.find(sub) Find a substring s.strip([chars]) Removes designated characters from string s.replace(old, new) Replaces instances of old substring with new substring … All return a (modified) copy of string Do not update original string CS-2301, D-Term 2014 Introduction
9
Lists have methods, too! l.append() l.sort() l.reverse()
Our friend l.sort() Sorts elements in place. May be high-to-low or low- to-high l.reverse() Reverses the list l.index(x) l.count(x) Returns index of first occurrence of x in list or count of x’s in list l.pop(i) l.remove(x) Removes ith element (pop) or first occurrence of x See p. 345, also Python documentation CS-2301, D-Term 2014 Introduction
10
Questions? CS-2301, D-Term 2014 Introduction
11
Definition — File A (potentially) large amount of information that lives a (potentially) very long time May be (much) larger than the amount of RAM in your computer (Usually) expected to outlive the running of your program (May be) expected to outlive the computer itself! Stored on Hard drive Flash drive Spread out across multiple disks Somewhere in the “cloud” On some other medium … CS-2301, D-Term 2014 Introduction
12
Files (continued) (Usually) stored as a sequence of bytes
Byte: an 8-bit character The standard unit of storage since 1964 Other data types built up from sequences of bytes Organization of data within file defined by application Text Numerical data Big databases Program code … Directory (a.k.a. folder) — a list names and locations of other files Maintained by operating system CS-2301, D-Term 2014 Introduction
13
Remember to close your files before exiting your program!
Using Files Must be Opened before use Tells OS to make file ready for access Must be Closed when finished Tells OS to “put the file away” Make it safe for long term storage Note: Most operating systems automatically close files that are still open when program exits Don’t depend on this! Stale data may live in volatile memory for long time Where it can become corrupted … … or forgotten … … or lost … before OS gets around to writing to disk! Remember to close your files before exiting your program! CS-2301, D-Term 2014 Introduction
14
Three other modes:–. 't' – text mode (default). 'b' – binary
Three other modes:– 't' – text mode (default) 'b' – binary '+' – update in place Open Gets a file read for use OS sets up internal tables May fetch copy off remote disk Validates protection, Etc. f = open(filename, mode) Built-in function Filename String of text Name of the file (as seen in directory), with extension Possibly including directory “path” Mode 'r' – read (default) 'w' – write (truncate to zero length) 'a' – append … (other modes — see Python documentation) CS-2301, D-Term 2014 Introduction
15
Close f.close() = open(filename, mode) File method Closes the file
Clears internal buffers I.e., puts it away safely Don’t forget to do this in your program! CS-2301, D-Term 2014 Introduction
16
Reading from files f = open(filename, mode) f.read()
Reads entire remaining contents of file into one (potentially humungous) string Line endings represented by '\n' characters “Remaining” means from where we left off reading most recently to end of file f.readline() Reads one line Including '\n' character (a.k.a. newline character) Returns line as a string f.readlines() Reads all of the lines Returns a list of strings Each representing one line — as from readline() CS-2301, D-Term 2014 Introduction
17
Reading from files (continued)
Homework #4 requires you to read multiple files Process each one More useful information about file reading:– §5.9.2 of textbook Chapter 7 of online Python tutorial In IDLE, select Help > Python Docs Click Contents tab, select The Python Tutorial Click Input and Output About 7 lines down! CS-2301, D-Term 2014 Introduction
18
Homework #4 Once you have opened a file, need to extract all of the individual words Add to a list How to do that? Questions? CS-2301, D-Term 2014 Introduction
19
Writing to a file Also required in Homework #4
f = open(outputfilename, 'w') f.write(string) Writes the string at the end of the file Returns number of bytes written You need to supply trailing '\n' character To denote end of line You may write partial lines i.e., with no trailing '\n' You may write multiple lines at one time Until you are more skilled, concentrate on writing one full line at a time! CS-2301, D-Term 2014 Introduction
20
What next? Close the file!
Note:– both Python and OS keep contents of file buffered in memory I.e., volatile memory! Closing flushes the buffers to disk Where it is stored safe from (most) failures CS-2301, D-Term 2014 Introduction
21
Questions? CS-2301, D-Term 2014 Introduction
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.