Search code examples
pythontkinterevalcalculator

How do I make eval register integers such as 05 and 04 as valid?


I'm making a GUI calculator using tkinter and have run into a problem I can't seem to fix. Part of the requirements of the program is that the calculator works with input such as "02+04" which would return "6". When I try and enter this calculation into the Entry field I get the error

SyntaxError: invalid token

I've tried looking up how to get around and/or troubleshoot this error but have had no luck so far. Any help on how to make this work would be appreciated!


Solution

  • Using eval is frowned upon as pointed out in the comments and numerous places on the web. Even if input is sanitized, it's a design crutch.

    Having said that, it sounds like you're obligated to do it this way, so you may use this regex to replace leading zeros on numbers in the expression you plan to eval:

    self.answer = eval(re.sub(r"((?<=^)|(?<=[^\.\d]))0+(\d+)", r"\1\2", self.equation.get()))
    

    Breakdown of the regex:

    (                             # begin capturing group \1
     (?<=^)                       # positive lookbehind to beginning of line
           |                      # OR
            (?<=[^\.\d])          # positive lookbehind to non-digit, non-period character
                        )         # end capturing group \1
                         0+       # literal 0 one or more times
                           (\d+)  # one or more digits (capturing group \2)
    

    Don't forget to import re at the top of your script.