Velocity Reviews > parsing equations

# parsing equations

munehiro
Guest
Posts: n/a

 12-09-2003
hi all,

i have a question.
Given the string '3+2*6' i need to parse it and obtain the result, so
15. Does a module for this operation exists? i need to do simple
operations, but also on floating point numbers.

many thanks

Diez B. Roggisch
Guest
Posts: n/a

 12-09-2003
> i have a question.
> Given the string '3+2*6' i need to parse it and obtain the result, so
> 15. Does a module for this operation exists? i need to do simple
> operations, but also on floating point numbers.

Use the builtin function eval to evaluate an arbitrary python expression:

>>> eval("3+2*6")

15

Regards,

Diez

Peter Otten
Guest
Posts: n/a

 12-09-2003
Diez B. Roggisch wrote:

>> i have a question.
>> Given the string '3+2*6' i need to parse it and obtain the result, so
>> 15. Does a module for this operation exists? i need to do simple
>> operations, but also on floating point numbers.

>
> Use the builtin function eval to evaluate an arbitrary python expression:
>
>>>> eval("3+2*6")

> 15

Be aware that this is powerful:

>>> eval("cleanMyHarddisk()")

'done'

Just to make sure the OP is aware of the inherent danger of the unsuspecting
"arbitrary python expression"...

Peter

Diez B. Roggisch
Guest
Posts: n/a

 12-09-2003
> Be aware that this is powerful:
>
>>>> eval("cleanMyHarddisk()")

> 'done'
>
> Just to make sure the OP is aware of the inherent danger of the
> unsuspecting "arbitrary python expression"...

Yup - should have mentioned that.

Diez

munehiro
Guest
Posts: n/a

 12-09-2003
Diez B. Roggisch wrote:
> Use the builtin function eval to evaluate an arbitrary python

expression:
>
>
>>>>eval("3+2*6")

many thanks... it's exactly what i need