Week 10: Files and Strings
Submit PA3 to Gradescope
If you don't submit to Gradescope and get a nonzero score, you will receive a reflection grade of no higher than 15/30 points.
🎯 Objectives
Until now, everything your programs knew came from the code itself or from someone typing at the keyboard, and everything they found out vanished when the program ended. This week your programs start reading and writing files, so the data can live somewhere other than your code and the results can stick around.
Text from a file is rarely in the shape you want it, though.
A line ends with an invisible \n, has stray spaces, and holds several pieces of information in one string.
So the other half of this week is the toolkit for taking a string apart: slicing and string methods like strip() and split().
Along the way you'll meet an idea that explains a lot of puzzling bugs: a string can never be changed, but a list can, even from inside a function.
By the end of the week you should be able to:
- Write lines to a new text file, append lines to an existing one, and read a file one line at a time with a
withstatement. - Slice a string or a list, with and without the start, stop, and step, and use string methods such as
strip(),split(),join(),startswith(), and the case methods (upper(),lower()) to pull apart and transform text from a file. - Explain why a string method returns a new string instead of changing the original, and predict what happens to a list that a function changes in place.
Quiz 4 is next week
Quiz 4 covers Weeks 1–10, with its focus on Units 3 and 4 (Weeks 6–10), and is done without AI.
Expect to write one function and one test function for it.
Your instructor will share the details.
That makes this a good week to practice writing a small function and its pytest test from a blank file, without looking anything up.
"Rehearse a function and its test," below, walks you through it.
✅ Must do
These three are the core of the week. Do them first.
- The in-class activities, including the Reading/Writing Files activity. If you missed a class, work through its handout on your own.
- The reading: one of the options in "Read about it," below.
- PA3 Parts C and D, which read your program's data from a file and write its results to another. Submit the whole PA to Gradescope when it's done.
📚 Study menu (should do)
Class covered reading and writing files, slicing and string methods, and how strings and lists differ when you try to change them. Everything below is optional, but each item trains something Quiz 4 or PA3 needs. Pick what you need.
If you only have an hour
- Twenty minutes. "See what's really in a line," below, in Thonny.
- Ten minutes. "Slice it two ways," on paper first.
- Thirty minutes. "Rehearse a function and its test," with a timer running.
Read about it
Pick one option.
Python for Everybody: 8. Files and 7. Strings
- 8.1 Persistence, 8.2 Opening files, 8.3 Text files and lines, 8.4 Reading files, 8.5 Searching through a file, and 8.8 Writing files.
- 7.4 String slices, 7.5 Strings are immutable, 7.9 String methods, and 7.10 Parsing strings.
W3Schools: the reference-style skim
- Python Strings, with its Slicing Strings, Modify Strings, and String Methods subpages.
- Python File Handling, Python Read Files, and Python Write/Create Files.
A few things you can skip for now
PY4E 8.7 wraps open in try and except to catch a missing file. Handling errors is a special topic near the end of the course, so you can skip it for now.
W3Schools also has a "Delete Files" page, which nothing this week needs.
Neither book says much about the last objective, a list changed inside a function. PY4E 7.5 covers the string half, and "Who changed my list?" below covers the rest.
See what's really in a line
The activity in class used repr() to make the invisible parts of a line visible.
Take it one step further.
Type this into Thonny, but before you run it, write down what you think each print shows.
with open("scores.txt", "w") as file:
file.write("Ana, 92\n")
file.write("\n")
file.write(" Ben ,85 \n")
with open("scores.txt", "a") as file:
file.write("Cal, 78\n")
with open("scores.txt") as file:
for line in file:
print(repr(line))
print(repr(line.strip()), line.strip().split(","))
Then run the program a second time. Does scores.txt get longer? Why or why not?
Check your answers
Each line read from the file still ends in \n, and strip() removes it along with the spaces at both ends.
The blank line becomes '', and splitting that gives [''], a list with one empty string, not an empty list.
"Ben ,85" splits into ['Ben ', '85']. strip() only touched the ends of the whole line, so the space before the comma is still there, and each piece needs its own strip().
"Ana, 92" gives ' 92', but int(" 92") is still 92, because int ignores spaces around a number.
The file does not get longer on the second run: opening with "w" empties the file first, so the "a" only ever adds Cal once.
The rules you should be able to state afterward:
- A line from a file ends with
\n(except maybe the last one). Strip it before you compare it to anything. "w"replaces the file, and"a"adds to the end of it.- Strip the line, split it, and then strip each piece, because
strip()only ever touches the two ends of a string.
Slice it two ways
On paper, predict each slice, with word = "Madison" and nums = [10, 20, 30, 40, 50].
Then check yourself in the Shell.
| Expression | Your prediction |
|---|---|
word[0:3] |
|
word[3:] |
|
word[:-3] |
|
word[::2] |
|
word[::-1] |
|
word[2:100] |
|
word[4:2] |
|
nums[1:3] |
|
nums[::2] |
|
nums[-2:] |
Last, compare list(range(1, 7, 2)) with "abcdefg"[1:7:2].
Check your answers
'Mad', 'ison', 'Madi', 'Mdsn', 'nosidaM', 'dison', and ''.
Then [20, 30], [10, 30, 50], and [40, 50].
The range gives [1, 3, 5], and the slice gives 'bdf', the characters at positions 1, 3, and 5.
What this should leave you with:
- A slice works the same way on a string and on a list. Only the kind of thing you get back differs.
[start:stop:step]follows the same rules asrange(start, stop, step): start is included, stop is not.- A slice never raises an
IndexError.word[2:100]just stops at the end, andword[4:2]is empty.word[100]is still an error.
Who changed my list?
Trace this program on paper and write down each line it prints.
def shout(word):
word = word.upper()
return word
def add_cheer(items):
items.append("hooray")
def reset(items):
items = []
name = "pat"
shout(name)
print(name)
loud = shout(name)
print(loud)
team = ["go", "dukes"]
add_cheer(team)
print(team)
reset(team)
print(team)
line = " hello "
line.strip()
print(repr(line))
Check your answers
pat, PAT, ['go', 'dukes', 'hooray'], ['go', 'dukes', 'hooray'], and ' hello '.
shout can't change name. No function can, because strings are immutable. Its new string is lost unless you save the return value, as loud does.
add_cheer changes the one list that both items and team refer to, so the change shows up outside.
reset only points its own items at a brand-new list. team still refers to the old one, so nothing happens.
The last one is the bug behind a lot of PA3 Part C trouble: line.strip() makes a new string and throws it away. Write line = line.strip().
Step through it in Python Tutor if any answer surprised you, and watch the arrows: team and items point at the same list.
Look it up
Nobody memorizes every string method. You do need to know where to find them.
- In the Shell, try
help(str.split)andhelp(str.strip). What doessplitdo when you give it no argument at all? - Skim the official list of string methods in the Python docs. Find two methods you haven't used yet, and try each one on a string in the Shell.
dir("")lists every method a string has. Which ones start withis?
Rehearse a function and its test
Quiz 4 asks you to write a function and a test function, so practice the mechanics now, while nothing is at stake.
In a new folder, make two files.
Write the function in practice.py:
"""Practice for Quiz 4.
Name: Your Name
"""
def initials(full_name):
"""Return the capitalized first letter of each word, Ex "ada lovelace" -> "AL"."""
and its tests in test_practice.py:
import pytest
from practice import initials
def test_initials():
assert initials("ada lovelace") == "AL"
if __name__ == "__main__":
pytest.main()
Set a timer for fifteen minutes and fill in the function's body without looking anything up.
Then press Run in Thonny on the test file, so the pytest.main() block runs your tests.
Add at least two more assert lines that could catch a bug, like a name with extra spaces or with only one word.
For a second round, try count_long(words, n), which counts the strings in a list longer than n characters, and write its tests before its body.
Try an AI tutor
AI is a good drill partner for slicing and string methods, as long as it hands you the questions and not the answers. It also loves shortcuts this course hasn't covered, so tell it up front what you know.
"I am a CS1 student who knows
forandwhileloops, lists, sets, slicing, and the string methodsstrip,split,join,upper, andlower. Give me eight slicing and string-method expressions on one short string, one at a time. Wait for my prediction before telling me if I'm right.""Here is my function for reading a file. Don't rewrite it. Tell me which line would break on a blank line in the file, and let me fix it."
The thing to be skeptical about this week is shortcuts.
AI tends to reach for readlines(), try and except, and one-line comprehensions.
They aren't wrong, but you can't use what you can't explain on Quiz 4, and a loop over the file is easier to trace by hand.
🔭 Explore more
Finished early, or just curious? None of these are required.
- Download a book in plain text from Project Gutenberg and write a program that finds its longest line, or counts the lines that mention a word you choose.
- Write a tiny "mail merge": read names from one file and write a personalized greeting for each person to another.
- Find out what
str.partition,str.center, andstr.titledo, and whentitle()gives a surprising answer (try"don't stop".title()). - Look ahead: a list can be sliced, but can you assign to a slice? Try
nums[1:3] = [0]and explain what happened.
✍️ Reflection
Instructions
Download the Week 10 reflection template, type your answers into it, and submit the completed document.
The first three questions are quick; the short answers are the ones that matter. Question 4 is about how you tested your PA3 Parts C and D, so answer it after you submit. A few sentences each is plenty. Be specific and be honest.
Submit PA3 to Gradescope
If you don't submit to Gradescope and get a nonzero score, you will receive a reflection grade of no higher than 15/30 points.
1. What did you do this week? (Check all that apply.)
- Worked through the in-class activities
- Read the sections listed for one of the textbooks
- Finished PA3 Parts C and D
- Predicted the output in "See what's really in a line"
- Filled in the "Slice it two ways" table on paper
- Traced "Who changed my list?"
- Looked up string methods with
help()or the Python docs - Rehearsed a function and its test for Quiz 4
- Asked an AI tutor to drill me
- Tried something from "Explore more"
- Something else (tell us in the short answers)
2. Roughly how much time did you spend on CS 149 outside of class this week?
- Under 1 hour
- 1–2 hours
- 3–4 hours
- 5–6 hours
- 7+ hours
3. How ready do you feel to write a function and its test for Quiz 4?
- Ready: I can write both from a blank file without looking anything up
- Mostly: I can write the function, but the test file still trips me up
- Not yet: I need my notes or the PA to get started
- I haven't tried it yet
4. How did you test your program? Before you submitted PA3 Parts C and D to Gradescope, what files or calls did you try, and what could each one have caught? Did you try a file with a blank line, a comment line, or a line with extra spaces?
5. Give one string or file operation this week that did not do what you expected. It could be a slice that came out one character off, a split that left spaces behind, a method whose result you forgot to save, or a file that came out empty or doubled. Say what you expected, what happened, and the rule you were using that turned out to be wrong.
6. What is one thing you want gone over in class? Be as specific as you can: "why reset(team) didn't empty the list" is useful, and "strings" is not. Class time gets spent on whatever shows up most often in these answers.
7. Did you use an AI tool this week, and did it build your understanding or replace it? The honest test: could you write PA3's Part C loop again on a blank page, and say what each strip() and split() in it is for? If a video, article, or tutorial made something click, drop the link and one line on why it helped.
8. Paste your PA3 code, all four parts. If one of your string methods or slices surprised you along the way, say which one.