3

I want to separate a string based on comma, but when the string is within double quotes the commas should be kept as it is. For that I wrote the following code. However, the code given below does not seem to work. Can someone please help me figure out as to what the error is?

>>> from csv import reader
>>> l='k,<livesIn> "Dayton,_Ohio"'
>>> l1=[]
>>> l1.append(l)
>>> for line1 in reader(l1):
        print line1

The output which I am getting is:

['k', '<livesIn> "Dayton', '_Ohio"']

Whereas I want the output as: ['k', '<livesIn> "Dayton,_Ohio"'] i.e. I don't want "Dayton,_Ohio" to get separated.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Jannat Arora
  • 2,759
  • 8
  • 44
  • 70
  • You need to configure the dialect parameter. http://docs.python.org/2/library/csv.html#csv-fmt-params – nhahtdh Apr 29 '13 at 08:26
  • 1
    possible duplicate of [How to split but ignore separators in quoted strings, in python?](http://stackoverflow.com/questions/2785755/how-to-split-but-ignore-separators-in-quoted-strings-in-python) – Kobi Apr 29 '13 at 08:27
  • Why are you using csv to parse a string, and not a csv file? – bozdoz Apr 29 '13 at 08:28
  • 1
    @bozdoz That's fine, however a better way is `reader(StringIO(l))` – jamylak Apr 29 '13 at 08:29

1 Answers1

1

So here is a way.

>>> from csv import reader
>>> l='k,<livesIn> "Dayton,_Ohio"'
>>> l1=[]
>>> l1.append(l)
>>> for line in reader(l1):
...   print list((line[0], ','.join(line[1:])))
... 
['k', '<livesIn> "Dayton,_Ohio"']
karlcow
  • 6,977
  • 4
  • 38
  • 72