P01.7 · Strings and files
P01.7 L0 · Foundation 4 lessons · about 100 min Live · in review
Part of P01 Python from Zero in the Programming and Data track.
Data reaches a program as text. These four lessons treat a string as a numbered row of characters that can be indexed, sliced and searched but never changed, cut lines into fields with split and put values back into text with f-strings, read and write text files through open and pathlib, and end by turning the course’s study.csv into rows of numbers, first by hand and then with the csv and json modules.
What you need first. Values and types (P01.2), loops (P01.3), functions (P01.4), import (P01.5), and lists, tuples and dictionaries with their indexing and slicing (P01.6). Characters stored as numbers (P01.1.4) are recalled where they are used.
Lessons
Strings are sequences of characters P01.7.1 25 min
A string is a numbered row of characters. Count positions from 0 at the front or from -1 at the end, cut out slices with a start, a stop and a step, loop over the characters, and see why every string method hands back a new string.
Splitting, joining and formatting P01.7.2 25 min
Cut a line of text into its fields and glue the pieces back together: split written from scratch as a loop, then str.split, strip and join. Then put values into text with f-strings, widths and one decimal, and print the study table in straight columns.
Reading and writing text files P01.7.3 25 min
A file is a run of bytes on storage, found by its path. Open one with open inside a with block, write the three pinned lines of requirements.txt, read them back whole, line by line and in a loop, and see why encoding=‘utf-8’ is always written out.
Tables in files: CSV and JSON P01.7.4 25 min
Turn study.csv into a list of dictionaries, first by hand with split and int, then with csv.DictReader, which also copes with a comma inside quotes. Then save nested data as JSON and see what a round trip through JSON text changes.
The interactive
P01.7-X1 · String slicer. A line of text drawn as numbered boxes, counted from the front and from the end. Set start, stop and step and watch the slice take its characters one at a time, or switch to split and see the pieces that a separator cuts out. It lives in Strings are sequences of characters.