4 2. Sequences
4 2. Sequences
4 2. Sequences
SEQUENCES:
STRINGS, LISTS AND
FILES (PART II)
Rocky K. C. Chang
17 September 2014
(Adapted from John Zelle’s slides)
Objectives
• To understand the concept of objects, an active data type.
• To understand how string objects and list objects works in
Python.
• To understand basic file processing concepts and
techniques for reading and writing text files in Python.
• To be able to understand and write programs that process
textual information.
LET’S DO A
MONKEYSURVEY.
Native data types
• So far, we have learned some native data types in
Python.
• These data types are “passive” in the sense that they are
just data and they cannot compute.
• Some problems:
• We cannot easily use these data types to model real-life objects in
our problem solving.
• E.g., a circle (object) needs three float data, and a student record
(object) needs numbers and strings.
The concept of objects
• Languages that support object-oriented features provide
object data types, such as strings and lists.
• Example:
• myName = “Rocky Chang”
• myGrades = ["A+", "A", "B+", "B"]
• The difference with the object data types?
• Each object contains data (which are generally more complex).
• Each object also has methods operated in the data.
• In a program, we could request an object to perform
operation for us.
EXERCISE 5.1
o Create a string object, such as student =
“your_first_name, your_last_name, your
student ID”.
o Invoke some methods on the object, such as
student.split(), student.lower(),
student.upper(), student.capitalize().
A string object
split()
Rocky Chang
lower()
Your upper()
program
capitalize()
…
String methods
• For Python 3.0:
https://docs.python.org/3/library/stdtypes.html
• str.capitalize()
• str.casefold()
• str.center(width[, fillchar])
• str.count(sub[, start[, end]])
• ...
• str.title()
• str.translate(map)
• str.upper()
• str.zfill(width)
EXERCISE 5.2
Implement your pseudo-code for exercise 4.12.
You may consider using the split() method.
(You may download decodeUnicodes.py from
the course website)
Consider a solution to
Exercise 5.2.
Lists are also objects.
• One of the methods is append().
• What do these codes give us?
squares = []
for x in range(1,10):
squares.append(x*x)
print(squares)
• Try also
o aList = [“Rocky“, “Chang“]
o “Memory Dennis”.join(aList)
o “Memory Dennis”.join(“Rocky Chang”)
o “”.join(“Rocky Chang”)
o “”.join(aList)
EXERCISE 5.3
Create a list of “A”, “B”, “C”, “D”.
How do you use the join() method for lists
to return “ABCD”?
EXERCISE 5.4
Modify the solution to Exercise 5.2 by using a
list of strings and the methods append()
and join().
Input/Output as String Manipulation
• Program study: Download dateconvert.py from
the course website for converting a date in
mm/dd/yyyy to month, day, and year strings.
• E.g., 05/24/2014 -> May 24, 2014
• Pseudo-code:
• Input the date in mm/dd/yyyy format (dateStr).
• Split dateStr into month, day, and year strings.
• Convert the month string into a month number.
• Use the month number to lookup the month name.
• Create a new date string in the form “Month Day, Year”.
• Output the new date string.
Several things to note
• Use “/” in split().
• Use int(), instead of eval().
• int() can remove leading zeroes but not eval().
Using str()
• Converting a number to a string, e.g., str(100) “100”.
• We now have a complete set of type conversion
operations:
Function Meaning
float(<expr>) Convert expr to a floating point value
Source: http://www.pythonlearn.com/html-008/cfbook008.html
Reading/writing and saving a file
• Load the (part of) the file into the main memory.
• Read the file from the memory.
• Write the file to the memory.
• Saving will write the file in the memory to a secondary
storage.
EXERCISE 5.11
Try
infile = open(“a_text_file_of_your_choice","r")
data = infile.read()
print(data)
(You may need os.getpwd() and os.chdir() to find your
files.)
EXERCISE 5.12
Try
infile = open(“a_text_file_of_your_choice","r")
for i in range(10):
line = infile.readline()
print(line[:-1])
o How do you print the lines in a single line?
EXERCISE 5.13
Try
infile = open(“a_text_file_of_your_choice","r")
for line in infile.readlines():
print(line)
o Does the output look the same as the file’s?
Three file read methods
• <filevar>.read() – returns the entire remaining
contents of the file as a single (possibly large, multi-line)
string.
• <filevar>.readline() – returns the next line of the
file. This is all text up to and including the next newline
character.
• <filevar>.readlines() – returns a list of the
remaining lines in the file. Each list item is a single line
including the newline characters.
EXERCISE 5.14
Try
input_file = open(“an_existing_py_file", "r")
output_file = open(“clone.py", "w")
content = input_file.read()
output_file.write(content)
output_file.close()
Find the new clone.py file.
EXERCISE 5.15
Try
input_file = open("an_existing_py_file", "r")
output_file = open("another_existing_py_file",
"a")
content = input_file.read()
output_file.write(content)
output_file.close()
Open the output file.
Write and append methods
• Opening a file for writing prepares the file to receive data.
• If you open an existing file for writing, you wipe out the
file’s contents. If the named file does not exist, a new one
is created.
• It is important to close a file that is written to, otherwise
the tail end of the file may not be written to the file.
EXERCISE 5.16
o Download userfile.py from the course
website.
o Prepare an input file and use userfile.py to
generate batch usernames.
EXERCISE 5.17
o Modify userfile.py by replacing
print(uname, file=outfile) with
write(). Do you observe any difference in
the output file?
o How do you slightly modify the codes to
generate the same outputs?
END