[Tutor] accessing list from a string

Alan Gauld alan.gauld at btinternet.com
Wed Nov 26 01:43:46 CET 2008


"Bryan Fodness" <bryan.fodness at gmail.com> wrote 

>I have a list in a text file that is in the python format.,
> 
>    Positions = [2.5,2.8]

When you say "in the Python format" do you mean it 
is real Python codfe or just that it happens to look 
like Python?

If the latter what format is it really? If its a config file then 
the config parser will extract the string based on the key
(positions) for you. But you will still need to convert the 
string "[2.5,2.8]" to a list or tuple.

You could use eval to evaluate the string but that would 
be dangerous since the striong could be a malicious 
piece of code. But you can make it a lot safer by wrapping 
it in a function with known effect, thus:

s = "[2.5,2.8]"  # your string from the file

e = "tuple(" + e + ")"

x,y  = eval(e)    # x -> 2.5, y -> 2.8

Now if some crazy code gets read by error the eval 
will throw an error. Its not foolproof but it works for all but 
the most devious attacks.

If you don't like that then it's down to parsing the string 
and I'd suggest a regular expression is best to pull out 
the numbers unless the string is definitely fixed format/length.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list