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
Solution 1:
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.
Post a Comment for "How Do I Make Eval Register Integers Such As 05 And 04 As Valid?"