Python: Sequences: Strings, Lists and files (Part II)

Slides:



Advertisements
Similar presentations
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Advertisements

Introduction to C Programming
Introduction to C Programming
Computer Science 111 Fundamentals of Programming I Files.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
Introduction to C Programming
Topics This week: File input and output Python Programming, 2/e 1.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
General Computer Science for Engineers CISC 106 Lecture 02 Dr. John Cavazos Computer and Information Sciences 09/03/2010.
Lecture 16 – Open, read, write and close files.  At the end of this lecture, students should be able to:  understand file structure  open and close.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
CS190/295 Programming in Python for Life Sciences: Lecture 3 Instructor: Xiaohui Xie University of California, Irvine.
Input, Output, and Processing
Formatted Output CSE 1310 – Introduction to Computers and Programming 1.
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
16. Python Files I/O Printing to the Screen: The simplest way to produce output is using the print statement where you can pass zero or more expressions,
Files Tutor: You will need ….
3. COMPUTING WITH NUMBERS Rocky K. C. Chang September 10, 2015 (Adapted from John Zelle’s slides)
2. WRITING SIMPLE PROGRAMS Rocky K. C. Chang September 10, 2015 (Adapted from John Zelle’s slides)
Input and Output CMSC 120: Visualizing Information Lecture 4/10.
Formatted Output CSE 1310 – Introduction to Computers and Programming 1.
5. SEQUENCES: STRINGS, LISTS AND FILES (PART II) Rocky K. C. Chang September 16, 2015 (Adapted from John Zelle’s slides)
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
ENGINEERING 1D04 Tutorial 2. What we’re doing today More on Strings String input Strings as lists String indexing Slice Concatenation and Repetition len()
UMBC CMSC 104 – Section 01, Fall 2016
Topics Designing a Program Input, Processing, and Output
Python Variable Types.
Python: Experiencing IDLE, writing simple programs
Topics Introduction Hardware and Software How Computers Store Data
Chapter 2 - Introduction to C Programming
Containers and Lists CIS 40 – Introduction to Programming in Python
Object Oriented Programming
Lecture 24: print revisited, tuples cont.
Chapter 2 - Introduction to C Programming
Class 9 Reading and writing to files chr, ord and Unicode
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
Lecture 13 Input/Output Files.
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Topics Introduction to File Input and Output
CS190/295 Programming in Python for Life Sciences: Lecture 4
Chapter 2 - Introduction to C Programming
First Python Program Professor Hugh C. Lauer CS-1004 — Introduction to Programming for Non-Majors (Slides include materials from Python Programming: An.
Topics Introduction Hardware and Software How Computers Store Data
4. sequence data type Rocky K. C. Chang 16 September 2018
Chapter 2 - Introduction to C Programming
Rocky K. C. Chang September 18, 2018 (Based on Zelle and Dierbach)
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Rocky K. C. Chang 30 October 2018 (Based on Zelle and Dierbach)
CS190/295 Programming in Python for Life Sciences: Lecture 3
Topics Designing a Program Input, Processing, and Output
Programs written in C and C++ can run on many different computers
Topics Introduction to File Input and Output
CHAPTER 4: Lists, Tuples and Dictionaries
Topics Designing a Program Input, Processing, and Output
Chapter 2 - Introduction to C Programming
Terminal-Based Programs
Unit 3: Variables in Java
General Computer Science for Engineers CISC 106 Lecture 03
Topics Introduction to File Input and Output
Introduction to C Programming
2015 January February March April May June July August September
Introduction to Computer Science
Presentation transcript:

Python: Sequences: Strings, Lists and files (Part II) Dennis Y. W. Liu (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.

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 = "Dennis Liu" 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 1 Create a string object, such as student = "first_name last_names student_ID". Invoke some methods on the object, such as student.split(), student.lower(), student.upper(), student.capitalize().

… A string object student Methods Data split() Dennis Liu lower() Your program upper() capitalize() …

String methods For Python version 3 or above: https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str str.capitalize() str.casefold() str.center(width[, fillchar]) str.count(sub[, start[, end]]) ... str.title() str.translate(map) str.upper() str.zfill(width)

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) Other methods in https://docs.python.org/3/library/stdtypes.html#common-sequence-operations.

Turning a list into a string s.join(list): concatenate list into a string, using s as a separator. >> aList = ["Rocky", "Chang"] >> "Dennis Liu".join(aList) >> " ".join(aList) s.join(str): concatenate str into a string, using s as a separator. >> "Dennis Liu".join("Rocky Chang") >> "".join("Rocky Chang")

Exercise 2 Create a list of "A", "B", "C", "D". How do you use the join() method for lists to return "ABCD"?

Input/Output as String Manipulation Program study: 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.

Input/Output as String Manipulation # dateconvert.py # Converts a date in form "mm/dd/yyyy" to "month day, year" def main(): # get the date dateStr = input("Enter a date (mm/dd/yyyy): ") # split into components monthStr, dayStr, yearStr = dateStr.split("/") # convert monthStr to the month name months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] monthStr = months[int(monthStr)-1] # output result in month day, year format print("The converted date is:", monthStr, dayStr+",", yearStr) main()

Several things to note Use "/" in split(). Use int(), instead of eval(). int() can remove leading zeroes but not eval(). Try eval("05")

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 int(<expr>) Convert expr to an integer value str(<expr>) Return a string representation of expr eval(<string>) Evaluate string as an expression

String Formatting We have so far used some simple string operations to format the output. But it is difficult to format finer control with them. String object has a format method to perform more sophisticated formatting.

Exercise 3 Try Assign rocky = 100, dennis = 200, comp = 300. >> print("Rocky has ${0:0.2f} and Dennis has ${1:0.2f} and COMP has ${2:0.2f}".format(rocky, dennis, comp)) >> print("Rocky has ${2:0.2f} and Dennis has ${1:0.2f} and COMP has ${0:0.2f}".format(rocky, dennis, comp)) >> print("Rocky has ${3:0.2f} and Dennis has ${2:0.2f} and COMP has ${1:0.2f}".format(rocky, dennis, comp))

Exercise 4 Try >> dennis = 100. >> print("Dennis has ${0:0.2f}".format(dennis)) >> print("Dennis has ${0:1.2f}".format(dennis)) >> print("Dennis has ${0:5.2f}".format(dennis)) >> print("Dennis has ${0:10.2f}".format(dennis))

Exercise 5 Try >> import math >> print("The value of pi is {0:0.4f}".format(math.pi)) >> print("The value of pi is {0:0.20f}".format(math.pi)) >> print("The value of pi is {0:0.20}".format(math.pi))

The string format() method String formatting syntax: <template-string>.format(<values>) E.g., "The value of pi is {0:0.4f}".format(math.pi) Curly braces({}) inside the template-string marks “slots” into which the provided values are inserted. {<index>:<format-specifier>}, e.g., {0:0.4f} index: indicate which parameter to insert here One form of specifiers is <width>.<precision><type>. width: the number of spaces for printing the parameter precision: the number of decimal places f: the number to be formatted is a floating number

File (object) A file is a sequence of data that is stored in secondary memory (disk drive). Two types of files: text file and binary file A text file contains characters, structured as lines of text. A binary file a file formatted in a way that only a computer program can read. A text file usually contains more than one line of text. Lines of text are separated with a special character, the newline character.

How to end a line? (http://en.wikipedia.org/wiki/Newline) LF: Multics, Unix and Unix-like systems (GNU/Linux, OS X, FreeBSD, AIX, Xenix, etc.), BeOS, Amiga, RISC OS and others. CR: Commodore 8-bit machines, Acorn BBC, ZX Spectrum, TRS-80, Apple II family, Mac OS up to version 9 and OS-9 CR+LF: Microsoft Windows, DEC TOPS-10, RT-11 and most other early non-Unix and non-IBM OSes, CP/M, MP/M, DOS (MS-DOS, PC DOS, etc.), Atari TOS, OS/2, Symbian OS, Palm OS, Amstrad CPC

File Processing Open a file in a secondary storage. E.g., harddisk, CD-ROM and USB flash memory Read / Write the file. Save the file. Close the file.

Opening a file in a secondary storage To open a file infile = open("mbox.txt", "r") infile = open("mbox.txt", "w") If successful, a “file handler” will be returned. Source: http://www.pythonlearn.com/html-008/cfbook008.html

Reading/writing and saving a file What is actually done by the computer? Load (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 6 Try >> os.chdir("D:/") >> infile = open("comp1001.txt", "r") >> data = infile.read() >> print(data) Note: Remember to create a text file named, comp1001.txt, and save it to D: drive. You may type os.getcwd() to find your files in the current directory.

Exercise 7 Try >> infile = open("comp1001.txt", "r") >> for i in range(10): line = infile.readline() print(line[:-1]) How do you print the lines in a single line?

Exercise 8 Try Does the output look the same as the file’s? >> infile = open("comp1001.txt", "r") >> for line in infile.readlines(): print(line) 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 9 Try >> input_file = open("comp1001.txt", "r") >> output_file = open("clone.py", "w") >> content = input_file.read() >> output_file.write(content) >> output_file.close() Where is the new clone.py file?

Exercise 10 Try >> input_file = open("comp1001.txt", "r") >> output_file = open("existing_file.txt", "a") >> content = input_file.read() >> output_file.write(content) >> output_file.close() Open existing_file.txt. Compare it with comp1001.txt.

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 11 In A1 Q3, there are 16 possible states. Write the states into a text file named states.txt. Assume the states are stored in a list of strings, i.e., ["EEEE", "EEEW", …, "WWWW"].

End