Editor

Split a CSV Line

#150 · Parsing · Advanced · 135 XP · about 25 min

A CSV file stores a table as text, one row per line, with commas between the values. Splitting on every comma breaks as soon as a value contains a comma itself, so CSV lets you wrap a value in double quotes. Write split_csv(line) that splits one line into a list of field strings, following these rules:

  • Fields are separated by commas.
  • A field may be wrapped in double quotes. Inside the quotes a comma is an ordinary character, and two double quotes in a row ("") stand for one double quote. The wrapping quotes are not part of the value.
  • Spaces around a field, outside any quotes, are removed. Spaces inside quotes are kept.
  • An empty field (two commas in a row, or a comma at the start or end of the line) is the empty string.

Examples

split_csv('id,name,city')             # returns ['id', 'name', 'city']
split_csv('7, "Smith, Jo" , London')  # returns ['7', 'Smith, Jo', 'London']
split_csv('"She said ""hi""",,end')   # returns ['She said "hi"', '', 'end']

Constraints

  • line has 0 to 10,000 characters and no line breaks. An empty line holds one empty field.
  • Lines are well formed: a quote only opens at the start of a field (after any spaces), every opened quote is closed, and only spaces can come between a closing quote and the next comma.

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.