[Tutor] accessing list from a string
Lie Ryan
lie.1296 at gmail.com
Tue Nov 25 21:14:20 CET 2008
On Tue, 25 Nov 2008 06:59:13 -0800, Mark Tolonen wrote:
> "Bryan Fodness" <bryan.fodness at gmail.com> wrote in message
> news:fbf64d2b0811250641i208054f6h2a8f965942b356f0 at mail.gmail.com...
>> I have a list in a text file that is in the python format.,
>>
>> Positions = [2.5,2.8]
>>
>> and would like to grab the values.
>>
>> for line in file('list.txt'):
>> if line == Positions:
>> x1,x2=Positions
>>
>> I know this does not work. Is there a direct way to get my x1 and x2
>> values.
>
>>>> line = '[2.5,2.8]'
>>>> x1,x2 = eval(line)
>>>> x1,x2
> (2.5, 2.7999999999999998)
>
Don't give recommendations on eval without mentioning its danger. eval
can execute anything a python statement can, and that includes dangerous
statements that can be of security risk.
Instead, in python 2.6, you may use ast.literal_eval(). Which restrict
the eval to literal syntax only, and prohibit any function calling.
Alternatively, for previous versions of python, or for more flexibility,
you may use the safeeval like here: http://lybniz2.sourceforge.net/
safeeval.html
More information about the Tutor
mailing list