# parsing equations

Discussion in 'Python' started by munehiro, Dec 9, 2003.

1. ### munehiroGuest

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

munehiro, Dec 9, 2003

2. ### Diez B. RoggischGuest

> 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

Diez B. Roggisch, Dec 9, 2003

3. ### Peter OttenGuest

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

Peter Otten, Dec 9, 2003
4. ### Diez B. RoggischGuest

> 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

Diez B. Roggisch, Dec 9, 2003
5. ### munehiroGuest

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

munehiro, Dec 9, 2003