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 kBAryan needs to parse these lines into usable values:
line = "MemTotal: 16384000 kB"
# Goal: get "MemTotal" and 16384000He 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"]