string to list

Chris Rebert clp2 at
Thu Jun 14 10:06:18 CEST 2012

On Thu, Jun 14, 2012 at 12:40 AM, Hemanth H.M < at> wrote:
>>>> list(literal_eval('"aa","bb 'b'","cc"'))
> ['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.
>>> print '"aa","bb ' b'","cc"'
"aa","bb ","cc"
>>> print '''"aa","bb 'b'","cc"'''
"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.


More information about the Python-list mailing list