如何使 eval 寄存器整数(例如 05 和 04)有效? [英] How do I make eval register integers such as 05 and 04 as valid?

查看:21
本文介绍了如何使 eval 寄存器整数(例如 05 和 04)有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 tkinter 制作一个 GUI 计算器,但遇到了一个我似乎无法解决的问题.该程序的部分要求是计算器可以处理诸如02+04"之类的输入.这将返回6".当我尝试将此计算输入 Entry 字段时,我收到错误

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

语法错误:令牌无效

我已尝试查找如何绕过和/或解决此错误,但到目前为止还没有运气.任何有关如何使这项工作的帮助将不胜感激!

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!

推荐答案

使用 eval 是不受欢迎的,正如评论和网络上的许多地方所指出的那样.即使输入经过消毒,它也是一个设计拐杖.

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.

话虽如此,听起来您有义务这样做,因此您可以使用此正则表达式替换您计划 eval 的表达式中数字的前导零:

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()))

正则表达式分解:

(                             # 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)

不要忘记在脚本顶部import re.

这篇关于如何使 eval 寄存器整数(例如 05 和 04)有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆