List to STR to List
Alex Martelli
aleax at aleax.it
Sun Jul 14 16:35:10 EDT 2002
Larry wrote:
> I can convert a list to a string as follows:
>
> List1 = [1,2,3]
> String1 = str(L1)
>
> Is there now a way to convert my String1 variable back into a list???
There are several ways, but probably the most reasonable one is:
import rexec
alist = rexec.RExec().r_eval(String1)
All those 'r' stand for Restricted -- you want Restricted
execution (evaluation, in this case) to make sure no disaster
can happen, just in case the string may have been hacked
by some clever fellow.
If you must perform many such evaluations, it's speedier to:
import rexec
rr = rexec.RExec()
alist1 = rr.r_eval(String1)
alist2 = rr.r_eval(String2)
alist3 = rr.r_eval(String3)
i.e., instantiate rr once then use it over and over.
If you are ABSOLUTELY sure nobody can POSSIBLY have
tampered with String1 in ANY way, shape, or form, there
may be slightly handier ways to proceed. But since such
absolute certainty is rare, and unfounded some of the
time it's present, I suggest you stick to this approach.
Alex
More information about the Python-list
mailing list