Drill

ProblemsPython › text

Split one CSV line properly

hardtextPython

An import job reads a CSV where some fields legitimately contain commas, so splitting on the comma alone corrupts the data.

parse_csv_line(line: string) → list<string>

Solve it in the editor →

Where you start

def parse_csv_line(line: str) -> list[str]:
    

Worked examples

CallResult
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

The same problem in another language

More text problems in Python