string to list

B

bruce g

What is the best way to parse a CSV string to a list?

For example, how do I parse:
'AAA,"BBBB,CCCC,DDDD",EEE,FFF,GGG'
to get:
['AAA','BBB,CCC,DDDD','EEE','FFF','GGG’]

Thanks,
Bruce
 
S

Shambhu Rajak

This will do you job:
a = 'AAA,"BBBB,CCCC,DDDD",EEE,FFF,GGG'
b = []
for x in a.split(','):
.... if (x.find("\"") > -1):
.... x = x.strip("\"")
.... b.append(x)

If you want reduce the lines of code u can go for this option:
b = [x.strip("\"") for x in a.split(',')]


So Just Cheerz,
-Shambhu

-----Original Message-----
From: bruce g [mailto:[email protected]]
Sent: 14/06/2012 8:00 AM
To: (e-mail address removed)
Subject: string to list

What is the best way to parse a CSV string to a list?

For example, how do I parse:
'AAA,"BBBB,CCCC,DDDD",EEE,FFF,GGG'
to get:
['AAA','BBB,CCC,DDDD','EEE','FFF','GGG']

Thanks,
Bruce
 
P

Peter Otten

bruce said:
What is the best way to parse a CSV string to a list?

For example, how do I parse:
'AAA,"BBBB,CCCC,DDDD",EEE,FFF,GGG'
to get:
['AAA','BBB,CCC,DDDD','EEE','FFF','GGG’]
import csv
next(csv.reader(['AAA,"BBBB,CCCC,DDDD",EEE,FFF,GGG']))
['AAA', 'BBBB,CCCC,DDDD', 'EEE', 'FFF', 'GGG']

For multiple records:

list(csv.reader(text.splitlines(True)))
 
C

Chris Rebert

['aa', 'bb ', 'cc']

Strange?

Not really. You didn't properly escape the embedded quotation marks in
the string itself!
So before anything ever even gets passed to literal_eval(), that part
is parsed as two adjacent literals: '"aa","bb ' and b'","cc"'
In Python 3.x, the "b" prefix indicates a `bytes` literal rather than
a `str` literal.

Implicit adjacent string literal concatenation then occurs.
Thus:"aa","bb ","cc"
Compare:"aa","bb 'b'","cc"

But really, literal_eval() should not be used for CSV; it won't handle
unquoted fields at all, among other issues.

Cheers,
Chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,812
Latest member
GracielaWa

Latest Threads

Top