Split one CSV line properly
An import job reads a CSV where some fields legitimately contain commas, so splitting on the comma alone corrupts the data.
- Commas separate fields, except inside a double-quoted field.
- Inside a quoted field, two double quotes in a row mean one literal quote.
- The quotes themselves are not part of the value.
- An empty line gives an empty list; an empty field between two commas gives an empty string.
parse_csv_line(line: string) → list<string>
Where you start
def parse_csv_line(line: str) -> list[str]:
Worked examples
| Call | Result |
|---|---|
parse_csv_line("a,b,c") | ["a", "b", "c"] |
parse_csv_line("a,\"b,c\",d") | ["a", "b,c", "d"] |
parse_csv_line("\"say \"\"hi\"\"\",x") | ["say \"hi\"", "x"] |
parse_csv_line("a,,b") | ["a", "", "b"] |
Hint
Walk the line one character at a time carrying a single boolean: are we inside quotes right now.
Reference solution in Python
def parse_csv_line(line: str) -> list[str]:
if line == '':
return []
fields = []
cur = ''
quoted = False
i = 0
while i < len(line):
c = line[i]
if quoted:
if c == '"':
if i + 1 < len(line) and line[i + 1] == '"':
cur += '"'
i += 2
continue
quoted = False
i += 1
continue
cur += c
i += 1
elif c == '"':
quoted = True
i += 1
elif c == ',':
fields.append(cur)
cur = ''
i += 1
else:
cur += c
i += 1
fields.append(cur)
return fields