How to Split a String

Tim Chase python.list at
Thu Nov 29 21:27:10 CET 2007

> I need to convert the string: '(a, b, "c", d, "e")' into the
> following list ['a', 'b', 'c', 'd', 'e']. Much like a csv
> reader does. I usually use the split function, but this
> mini-monster wouldn't properly get split up due to those
> random quotations postgresql returns to me.

Uh...use the csv reader? :) No need to reinvent the parsing wheel.

 >>> import csv
 >>> from StringIO import StringIO
 >>> s = 'a,b,"c",d,"e"'
 >>> csv.reader(StringIO(s)).next()
['a', 'b', 'c', 'd', 'e']

If you really have the parens in your string too, you can peal 
them off first with "s[1:-1]"

 >>> s = '(a,b,"c",d,"e")'
 >>> csv.reader(StringIO(s[1:-1])).next()
['a', 'b', 'c', 'd', 'e']

or strip any/all parens:

 >>> s = '(a,b,"c",d,"e")'
 >>> csv.reader(StringIO(s.lstrip('(').rstrip(')'))).next()
['a', 'b', 'c', 'd', 'e']


More information about the Python-list mailing list