string to list

Chris Rebert clp2 at rebertia.com
Thu Jun 14 04:06:18 EDT 2012


On Thu, Jun 14, 2012 at 12:40 AM, Hemanth H.M <hemanth.hm at gmail.com> 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.
Thus:
>>> print '"aa","bb ' b'","cc"'
"aa","bb ","cc"
Compare:
>>> 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.

Cheers,
Chris



More information about the Python-list mailing list