WeCodeAcademy

Step 2: Parse the lines with a regular expression

A regular expression describes the shape of a line. Named groups (?P<name>...) give each part a name, so m.groupdict() returns a ready-made dictionary. Lines that do not match are kept aside with their line numbers instead of being silently thrown away, so you can see how much of the log you could not read.

Examplepython
Open in editor »

Read the pattern piece by piece: a date, a time, then \S+ (any run of non-space characters) for the IP and path, [A-Z]+ for the method, three digits for the status and digits for the milliseconds. Converting status and ms to int straight away means later code can compare and add them.

Your turn: write the code

Write parse_status(line) that returns the status code (an int) from a line like GET /home 200, or None if the line does not end with a 3-digit status. Print the result for GET /home 200, GET /x 404 and garbage.

Quick check

Why keep unreadable lines aside instead of ignoring them?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.