← Home

035. Split() Method

Parse structured text by splitting on delimiters

035. Split() Method

RAM Manager: Parsing /proc Output

Linux’s /proc/meminfo looks like this:

MemTotal:       16384000 kB
MemFree:         4096000 kB
MemAvailable:    8192000 kB
Buffers:          512000 kB

Aryan needs to parse these lines into usable values:

line = "MemTotal:       16384000 kB"
# Goal: get "MemTotal" and 16384000

He also needs to parse process command lines from /proc/PID/cmdline which uses null bytes as separators, and split filesystem paths for display.

His parse_meminfo_line uses split("//") instead of split("/"), and his get_words crashes with a ValueError. Fix both.


πŸ’‘ Fun fact: The Linux /proc filesystem Aryan is parsing was invented in the 1980s as a way to expose kernel data as ordinary files. Every /proc/meminfo line uses split() under the hood in nearly every monitoring tool β€” from htop to psutil β€” making string splitting one of the most-executed operations on a running Linux system.

⚠️ Watch out: "a b".split(" ") (with an explicit space) returns ["a", "", "b"] β€” the extra space becomes an empty string in the list. But "a b".split() (no argument) returns ["a", "b"]. Beginners almost always want the no-argument version when splitting on whitespace.

πŸ€” Think about it: split() and join() are inverses of each other. If ",".join(["a","b","c"]) gives "a,b,c", what does "a,b,c".split(",") give? And what happens if you round-trip a string that already contains the separator character β€” for example, splitting a CSV field that contains a comma inside quotes?

Learning objectives

  • Use split() to parse delimited strings
  • Use split() with no args to split on whitespace
  • Strip whitespace from split results

Key concepts

  • split()
  • parsing
  • delimiters

Try it

Concept detail

str.split(sep, maxsplit) splits a string and returns a list.

split() β†’ splits on ANY whitespace, collapses multiple spaces, removes empty strings split(β€œ,”) β†’ splits on comma; does NOT strip spaces from the parts split(β€œ/”, 2) β†’ splits at most 2 times; the rest stays in the last element

Critical differences: β€œa b c”.split() β†’ [β€œa”, β€œb”, β€œc”] (handles multiple spaces) β€œa b c”.split(β€œ β€œ) β†’ [β€œa”, β€œβ€, β€œb”, β€œβ€, β€œc”] (keeps empty strings!) β€œβ€.split(β€œβ€) β†’ ValueError! (empty separator is forbidden)

Common patterns:

Parse β€œkey: value” lines

key, value = line.split(β€œ:”, 1) # maxsplit=1 prevents split on value’s colons

Strip each field after splitting

[p.strip() for p in line.split(β€œ,”)]

Parse paths safely

path.strip(β€œ/”).split(β€œ/”) # removes leading/trailing slash before splitting

The inverse of split() is join(): β€œ, β€œ.join([β€œa”, β€œb”]) == β€œa, b”

Solution

def parse_csv_line(line):
    parts = line.split(",")
    return [p.strip() for p in parts]

def get_words(sentence):
    return sentence.split()

def parse_path(path):
    return path.strip("/").split("/")

Tests

def test_csv_basic():
    result = parse_csv_line("Alice,30,Engineer")
    assert result == ["Alice", "30", "Engineer"]

def test_csv_with_spaces():
    result = parse_csv_line("Alice, 30, Engineer")
    assert result == ["Alice", "30", "Engineer"]

def test_get_words():
    result = get_words("hello world foo")
    assert result == ["hello", "world", "foo"]

def test_get_words_extra_spaces():
    result = get_words("  hello   world  ")
    assert result == ["hello", "world"]

def test_get_words_no_valueerror():
    # split("") raises ValueError β€” make sure it doesn't
    try:
        result = get_words("test")
        assert result == ["test"]
    except ValueError:
        assert False, "split('') raises ValueError β€” use split() with no argument"

def test_parse_path():
    result = parse_path("/usr/local/bin")
    assert result == ["usr", "local", "bin"]

Resources