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)
text contains no = at all, raise ValueError("missing '=' in pair").=) is empty, raise ValueError("empty key")."key:value" (note the colon).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")
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.
= 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."=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").
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 =).
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.
def parse_pair(text):
if "=" not in text:
raise ValueError("missing '=' in pair")
key, value = text.split("=", 1)
if key == "":
raise ValueError("empty key")
return f"{key}:{value}"
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.