Parsing Errors

Parsing Errors

Parsers deal with malformed input constantly — this problem is about raising the right error for each distinct way input can be broken, not just one generic failure.

Write a function that parses a "key=value" string:

parse_pair(text)
  • If text contains no = at all, raise ValueError("missing '=' in pair").
  • If the key (everything before the first =) is empty, raise ValueError("empty key").
  • Otherwise, return "key:value" (note the colon).

Examples

parse_pair("name=Ada")   // → "name:Ada"
parse_pair("a=b=c")      // → "a:b=c"   (split only on the FIRST "=")
parse_pair("no-equals")  // raises ValueError("missing '=' in pair")
parse_pair("=value")     // raises ValueError("empty key")

Walkthrough

Thinking it through

The interesting part of this problem isn't the string manipulation — it's recognizing that "malformed input" isn't one failure mode, it's several, and each deserves its own clear error message rather than one catch-all.

Two distinct failure cases

  1. No = at all"no-equals" isn't a key-value pair in any sense. This should fail loudly and immediately, before you even try to split it.
  2. Empty key"=value" does contain an =, so it splits fine, but the result (an empty string as a key) is almost certainly not what the caller wanted.

Both raise ValueError, but with different messages — that's deliberate. A caller catching the exception can inspect str(e) to distinguish exactly what went wrong, without needing two different exception types for what's fundamentally the same category of problem ("this text isn't a valid pair").

Why split with a limit

text.split("=", 1) splits only on the first =, capping it at 2 pieces. Without the limit, "a=b=c".split("=") would produce three pieces (["a", "b", "c"]), which doesn't unpack into key, value = .... Limiting the split keeps everything after the first = — including any further = characters — as part of the value, which matches how key=value pairs are conventionally parsed (think environment variables or query strings, where the value itself can contain =).

Order of checks matters

Check for a missing = before attempting to split. If you split first and there's no =, text.split("=", 1) just returns [text] — a single-element list — and unpacking it into key, value raises a confusing, unrelated ValueError: not enough values to unpack, instead of your clear, intentional message.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.