1

I have a address like

line = 12345 North Drive,,"Palm Retreat, CO",CO,92261  

When I split I get

line.split(",") 
['12345 North Drive', '', '"Palm Retreat', ' CO"', 'CO', '92261']  

All I want is

'12345 North Drive', '', '"Palm Retreat CO"', 'CO', '92261']  

What is that I am missing here?

daydreamer
  • 87,243
  • 191
  • 450
  • 722

2 Answers2

4

split() is working as intended; it does not care about quotes. You may want to take a look at the csv module in conjunction with StringIO: you put your string in a StringIO object (which makes it look like a file) and then pass it on to csv.reader. Something like this:

import csv
from cStringIO import StringIO

s = "12345 North Drive,,\"Palm Retreat, CO\",CO,92261"
s = StringIO(s)
reader = csv.reader(s, delimiter=",")
for row in reader:
    print row

Update: actually, since csv.reader works with any iterable that yields lines (not just files), you can simply pass a list of lines to csv.reader without going through the StringIO bit.

Tamás
  • 47,239
  • 12
  • 105
  • 124
0

You should use the csv module to handle CSV data.

MRAB
  • 20,356
  • 6
  • 40
  • 33