Parsing turns text into fields a program can use. Choose a technique that fits the input: split simple delimited records, use the csv module when fields may contain delimiters, or use a regular expression to extract parts of a patterned line. section 16.4 section 21.2.3 section 21.2.4
For delimited text:
- Use `line.split('|')` when a pipe separates every field and cannot occur inside a value. For example, `Illinois|1979/01/01|17.48|994` becomes four strings; convert values to other types as needed. section 21.2.3
- Use `csv.reader(file, delimiter='|')` to read pipe-delimited files. For comma-delimited data, its handling of quoted fields matters: a comma inside a quoted date is part of the value, not a field boundary. section 21.2.4
- Use `split()` without an argument to split on whitespace, or supply a delimiter. A second argument limits the number of splits: `'a b c d'.split(' ', 1)` gives `['a', 'b c d']`. section 6.4.1
Extract a name and phone number
A record can have the form `surname, firstname middlename: phonenumber`, with an optional middle name and area code. A regular expression can match those optional parts; named groups let `result.group('first')` and `result.group('phone')` retrieve fields. Check whether the search returned a match before reading groups, and allow for a missing middle name. section 16.4
[-a-zA-Z]+, [-a-zA-Z]+( [-a-zA-Z]+)?: (\d{3}-)?\d{3}-\d{4}
The full pattern combines name-character classes, required and optional repetitions, punctuation, and the phone-number pattern. section 16.4
A delimiter alone is not always enough to describe a file. If values can contain that delimiter, prefer `csv.reader` over adding special cases to a series of `split()` calls. section 21.2.4












