Programming from zero

Split a log line into its parts

mediumNumbers and strings Must-do

Problem statement

A log line has four parts separated by spaces: date, time, level, and message. The message itself may contain spaces. Given:

line = "2026-09-24 10:15:32 ERROR disk full on /var"

print the level and the message on two lines, as Level: ERROR and Message: disk full on /var.

Examples

Example 1

Input: line = "2026-09-24 10:15:32 ERROR disk full on /var"

Output: Level: ERROR Message: disk full on /var

Hints

Approach

Optimal

.split(" ") cuts a string at every space and returns a list of pieces. The trouble is that the message contains spaces too, so a plain split gives you seven pieces. Passing a second argument, maxsplit, tells Python to stop after that many cuts: split(" ", 3) returns exactly four pieces, and the last one keeps the rest of the line intact. You can then unpack the four pieces straight into named variables: date, time, level, message = .... Named variables are much clearer than writing parts[2] and parts[3] everywhere.

Python
line = "2026-09-24 10:15:32 ERROR disk full on /var"
date, time, level, message = line.split(" ", 3)
print(f"Level: {level}")
print(f"Message: {message}")

Follow-up questions

  • Also print the hour only, by splitting time on ":".
  • Print Needs attention if the level is ERROR or CRITICAL.

Frequently asked questions

The number of names on the left does not match the number of pieces on the right. Without maxsplit, the split returns more than four pieces, so four variables are not enough.