encoding and decoding repr'd version of strings

Tim Peters tim.one at comcast.net
Mon Jun 3 16:32:02 EDT 2002


[Daniel Parisien]
> is there an codec that bundles with python so you can transform strings
> into the repr'd (escaped) version and back?

Not now; there may be in 2.3.  Getting the escaped version is trivial, i.e.
that's what repr(string) has always done.  It's the other direction that's
missing.

> If not, how easy would it be to code?

It's a matter of rearranging code that already exists (at C level).


> I don't want to use eval(...) because I don't trust the  source of the
> string and I might mistakenly eval an expression like "' '*(2**30)" which
> would allocate about 1 GB of data (eek!)

Use eval anyway, but first pass the putative string literal through
tokenize.py to ensure that it really is a string literal.






More information about the Python-list mailing list