How to convert a Python csv string to array?

PythonServer Side ProgrammingProgramming

Easiest way is to use the str.split method to split on every occurance of ',' and map every string to the strip method to remove any leading/trailing whitespace. For example,

>>> s = "1, John Doe, Boston, USA"
>>> print map(str.strip, s.split(','))
['1', 'John Doe', 'Boston', 'USA']

If you have a multi-line string with multiple lines of csv, you can split on \n and then split and strip each line. For example,

>>> s = "1, John Doe, Boston, USA\n2, Jane Doe, Chicago, USA"
>>> print [map(str.strip, s_inner.split(',')) for s_inner in s.splitlines()]
[['1', 'John Doe', 'Boston', 'USA'], ['2', 'Jane Doe', 'Chicago', 'USA']]

The csv module in Python also has a helper function, reader for achieving the same result. For example,

>>> s = "1, John Doe, Boston, USA\n2, Jane Doe, Chicago, USA".splitlines()
>>> import csv
>>> x = csv.reader(s)
>>> list(x)
[['1', ' John Doe', ' Boston', ' USA'], ['2', ' Jane Doe', ' Chicago', ' USA']]
raja
Published on 14-Dec-2017 14:16:00
Advertisements