#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2003
    Posts
    81
    Rep Power
    12

    Calculate String


    Help, I have a string that contains a mathematical expression(very simple can only contain +,-,*,and\) How do I get python to evaluate that string? Thanks, btw I need to ensure that the divison is integer division. Thanks!
    example
    str="3+5*2\1"
    Last edited by jimo9; March 30th, 2004 at 11:30 PM.
  2. #2
  3. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    14
    The eval() function is what you want:
    Code:
    >>> eval("1+1/2")
    1
    >>> eval("1+1/2.0")
    1.5
    >>> eval("1+1//2")
    1
    >>> eval("1+1//2.0")
    1.0
    >>> string = "1+1/2.0".replace('/','//')
    >>> string
    '1+1//2.0'
    Grim

IMN logo majestic logo threadwatch logo seochat tools logo