Split a CSV line with quoted fields

hardPipelines~35 min · 10 tests

line.split(",") works right up until a product is called Mug, large. CSV has a small quoting rule, and almost every broken import breaks on it. Write the parser.

Write parse_csv_line(line) that returns the fields as a list of strings:

  • Fields are separated by commas. An empty line is one empty field: [""].
  • A field that starts with " is quoted. Inside it, commas are plain text and "" stands for one ". The field ends at the next lone ".
  • After a closing quote, the next character must be a comma or the end of the line. Anything else raises ValueError.
  • A quote that is never closed raises ValueError.
  • In an unquoted field, a " that isn’t the first character is just a character.
  • Don’t strip whitespace. Don’t use the csv module.
>>> parse_csv_line('7,"Mug, large","say ""hi""",')
['7', 'Mug, large', 'say "hi"', '']
solution.pyPython 3.14 · Pyodide

Press ⌘ ↵ or Run to check the visible tests. Submit runs the hidden ones too. Everything runs in your browser.

⌘ ↵ to run