Problem 223350 · medium · Level 02 Linear Data Structures

Writing a Spreadsheet Export

py-join · strings · csv

Write to_csv(rows) that turns a table into the text of a comma-separated file. rows is a list of rows; each row is a list of values, which are strings, integers, floats or None.

  • Each value becomes text: None becomes the empty string, anything else becomes str(value).
  • A text that contains a comma ,, a double quote " or a newline must be quoted: every " inside it is doubled, and the whole text is wrapped in double quotes.
  • The fields of a row are separated by commas, and the rows by "\n". There is no newline after the last row.

Examples

Input:  rows = [["name", "age"], ["Ana", 31], ["Ben, Jr.", None]]
Output: 'name,age\nAna,31\n"Ben, Jr.",'

Input:  rows = [['say "hi"', 2.5]]
Output: '"say ""hi""",2.5'

Input:  rows = [[]]
Output: ''

Printed, the first output looks like this:

name,age
Ana,31
"Ben, Jr.",

Constraints

  • 0 <= len(rows) <= 10**4, each row has at most 50 values
  • The output has at most 10**6 characters.

Goals

  • Join converted pieces with a separator instead of adding strings in a loop
  • Quote a field only when it needs it, doubling any quote inside
  • Build multi-line text as a list of lines joined once
Starting Python…