How to Split a String
Grant Edwards
grante at visi.com
Thu Nov 29 16:11:02 EST 2007
On 2007-11-29, Grant Edwards <grante at visi.com> wrote:
>> One solution:
>>
>> >>> s = '(a, b, "c", d, "e")'
>> >>> print [x.strip('" ') for x in s.strip('()').split(',')]
>> ['a', 'b', 'c', 'd', 'e']
>
> That fails when a quoted string contains commas:
>
>>>> s = '(a, b, "c", d, "e,f,g")'
>>>> print [x.strip('" ') for x in s.strip('()').split(',')]
> ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>
> I presume the correct result would be
>
> ['a', 'b', 'c', 'd', 'e,f,g']
You can get that result easily with the csv module:
>>> repr(ss)
'\'a,b,"c",d,"e,f,g"\''
>>> for row in csv.reader([ss],skipinitialspace=True):
... print row
...
['a', 'b', 'c', 'd', 'e,f,g']
--
Grant Edwards grante Yow! I'm not available
at for comment..
visi.com
More information about the Python-list
mailing list