Text Data, Files, and Exceptions
Text Data, Files, and Exceptions
§ Strings, revisited
§ Formatted output
§ File Input/Output
§ Errors and Exceptions
String representations
A string value is represented as a sequence of characters delimited by quotes
Quotes can be single (') or double (")
>>> excuse = 'I am sick'
What if ' or " is one of >>> excuse = "I am sick"
the string characters? >>> excuse = 'I'm sick'
SyntaxError: invalid syntax
What if the string includes >>> excuse = "I'm sick"
sick”
both ' and "? >>> excuse = "I'm "sick""
SyntaxError: invalid syntax
Escape sequence \' or \" is used to >>> excuse = 'I'm "sick"'
SyntaxError: invalid syntax
indicate that a quote is not the string >>> excuse = 'I\'m "sick"'
delimiter but is part of the string >>> excuse
value 'I\'m "sick"'
>>> print(excuse)
Function print() interprets the I'm "sick”
"sick"
>>> excuse = 'I\'m ...\n... "sick"'
escape sequence >>> excuse
'I\'m ...\n... "sick"'
Another example: >>> print(excuse)
• \n is an escape sequence that I'm ...
... "sick" excuse.py
represents a new line 2
Introduction to Computing Using Python
-5 -4 -3 -2 -1
s = 'A p p l e'
0 1 2 3 4
s[0] = 'A'
s[1] = 'p' >>>
>>>
s = 'Apple'
s[0]
'A'
s[2] = 'p' >>> s[1]
'p'
s[3] = 'l' >>> s[4]
'e'
s[4] = 'e'
3
Introduction to Computing Using Python
s = 'A p p l e'
0 1 2 3 4
>>> s = 'Apple'
s[0:2] = 'A' p'
'A >>> s[0:2]
'Ap'
s[1:4] = 'p' p l'
'p >>> s[1:4]
>>> s = 'Apple'
>>> s[0]
'ppl'
'A' s[2:5]
s[2:5] = 'p' l e'
'p >>>
>>> s[1]
'ple'
'p' s[2:]
>>>
s[2:] = 'p 'l'
l e' >>> s[4]
'ple'
'e' s[:2]
>>>
s[:2] = 'A p' 'Ap'
>>> s[-3:-1] 4
s[-3:-1] = 'p l' 'pl'
Let’s practice!
• Jupyter Notebook:
Canvas –> Modules –> Text Data and File Input/Output
5
Introduction to Computing Using Python
Write Python expressions using list lst and the indexing operator that
evaluate to:
6
Introduction to Computing Using Python
String methods
Usage Explanation
s.capitalize() returns a copy of s with first character
capitalized
s.count(target) returns the number of occurences of
target in s
Strings are s.find(target) returns the index of the first
occurrence of target in s
immutable; none
of the string s.lower() returns lowercase copy of s
methods modify s.replace(old, new) returns copy of s with every
string link occurrence of old replaced with new
s.split(sep) returns list of substrings of s,
delimited by sep
s.strip() returns copy of s without leading and
trailing whitespace
s.upper() returns uppercase copy of s 8
Let’s practice!
• Jupyter Notebook:
Canvas –> Modules –> Text Data and File Input/Output
9
Introduction to Computing Using Python
10
Introduction to Computing Using Python
String methods
Suppose we need to pick up the date and time components of string event
events.py
Solution: replace punctuation with blank spaces
Usage Explanation
str.maketrans(old, new) returns a table mapping characters in
string old to characters in string new
s.translate(table) returns a copy of s in which the original
characters are replaced using the
mapping described by table 11
Introduction to Computing Using Python
print.py
12
Introduction to Computing Using Python
13
Introduction to Computing Using Python
boa\n
boa
cat
cat\n
dog
dog\n
>>>
print.py
14
Introduction to Computing Using Python
boa\n
boa
cat\n
cat
dog\n
dog
>>> for pet in pets:
print(pet, end=', ')
print.py
print.py
format string
print('{}:{}:{}'.format(hour, minute, second))
placeholders 18
Introduction to Computing Using Python
print.py
19
Introduction to Computing Using Python
1 1 2
2 4 4
3 9 8
4 16 16 reserves 3 spaces for 2**i
5 25 32
6 36 64 21
7 49 128
Introduction to Computing Using Python
Inside the curly braces of a placeholder, we can specify the field width
width, the
type of the output,
output and the decimal precision
>>> n = 10
>>> '{:b}'.format(n)
'1010'
Type Explanation >>> '{:c}'.format(n)
'{:7.2f}'
b binary '\n'
c character
>>> '{:d}'.format(n)
'10'
field width
d decimal
>>> '{:X}'.format(n) decimal precision
'A'
X hexadecimal >>> '{:e}'.format(n)
'1.000000e+01'
e scientific >>> '{:7.2f}'.format(n)
' 10.00'
f fixed-point >>>
print.py 24
Introduction to Computing Using Python
Mode Description
r Reading (default)
w Writing (if file exists, content is wiped)
a Append (if file exists, writes are appended)
r+ Reading and Writing
t Text (default)
b Binary
File methods
There are several “file” types; they all support similar “file” methods
• Methods read() and readline() return the characters read as a string
• Methods readlines() returns the characters read as a list of lines
• Method write() returns the number of characters written
Usage Description
infile.read(n) Read n characters starting from cursor; if fewer
than n characters remain, read until the end of file
infile.read() Read starting from cursor up to the end of the file
infile.readline() Read starting from cursor up to, and including, the
end of line character
infile.readlines() Read starting from cursor up to the end of the file
and return list of lines
outfile.write(s) Write string s to file outfile starting from cursor
infile.close(n) Close file infile 29
Introduction to Computing Using Python
Reading a file
1 The 3 lines in this file end with the new line character.\n
2 \n
3 There is a blank line above this line.\n
example.txt
When the file is opened, a cursor is associated with the opened file
Reading a file
1 The 3 lines in this file end with the new line character.\n
2 \n
3 There is a blank line above this line.\n
example.txt
When the file is opened, a cursor is associated with the opened file
32
Introduction to Computing Using Python
Please explain the purpose of each function and add appropriate docstring
Example:
def f1(filename):
'returns ...'
return len(content)
ch4.py
33
Introduction to Computing Using Python
Please explain the purpose of each function and add appropriate docstring
Example:
def f2(filename):
'returns ...'
infile = open(filename)
content = infile.read()
infile.close()
wordList = content.split()
return len(wordList)
ch4.py
34
Introduction to Computing Using Python
Please explain the purpose of each function and add appropriate docstring
Example:
def f3(filename):
'returns ...'
return len(lineList)
ch4.py
35
Introduction to Computing Using Python
1 T
This is the first line. Still the first line…\n
2 Now we are in the second line.\n
3 Non string value like 5 must be converted first.\n
4 Non string value like 5 must be converted first.\n
test.txt
Types of errors
37
Introduction to Computing Using Python
Syntax errors
Syntax errors are errors that are due to the incorrect format of a Python
statement
• They occur while the statement is being translated to machine
language and before it is being executed.
>>> (3+4]
SyntaxError: invalid syntax
>>> if x == 5
SyntaxError: invalid syntax
>>> print 'hello'
SyntaxError: invalid syntax
>>> lst = [4;5;6]
SyntaxError: invalid syntax
>>> for i in range(10):
print(i)
SyntaxError: expected an indented block
38
Introduction to Computing Using Python
>>> 3/0
Traceback (most recent call last):
File "<pyshell#56>", line 1, in <module>
3/0
ZeroDivisionError: division by zero
39
Introduction to Computing Using Python
>>> int('4.5')
Traceback (most recent call last):
File "<pyshell#61>", line 1, in <module>
int('4.5')
ValueError: invalid literal for int() with
base 10: '4.5'
41
Introduction to Computing Using Python
Exception types
Exception Explanation
KeyboardInterrupt Raised when user hits Ctrl-C, the interrupt key
OverflowError Raised when a floating-point expression evaluates to a value that is
too large
ZeroDivisionError Raised when attempting to divide by 0
IOError Raised when an I/O operation fails for an I/O-related reason
IndexError Raised when a sequence index is outside the range of valid indexes
NameError Raised when attempting to evaluate an unassigned identifier (name)
TypeError Raised when an operation of function is applied to an object of the
wrong type
ValueError Raised when operation or function has an argument of the right
42
type
but incorrect value