【发布时间】:2014-11-10 22:54:43
【问题描述】:
我正在制作一个计算器,用户在其中输入一个表达式,例如 3*2+1/20,然后我使用 eval 来显示答案。
是否有一个函数可以让我在其他基础(bin、oct、hex)中做同样的事情?
【问题讨论】:
标签: python tkinter calculator
我正在制作一个计算器,用户在其中输入一个表达式,例如 3*2+1/20,然后我使用 eval 来显示答案。
是否有一个函数可以让我在其他基础(bin、oct、hex)中做同样的事情?
【问题讨论】:
标签: python tkinter calculator
【讨论】:
没有; eval用于解析Python,the base of numbers in Python code is fixed。
如果您坚持使用这种方法,可以使用正则表达式替换以 0x 为数字添加前缀,但最好构建一个解析器,例如使用 int(string, base) 来生成数字。
如果你真的想走 Python 路线,这里有一个基于令牌的转换:
import tokenize
from io import BytesIO
def tokens_with_base(tokens, base):
for token in tokens:
if token.type == tokenize.NUMBER:
try:
value = int(token.string, base)
except ValueError:
# Not transformable
pass
else:
# Transformable
token = tokenize.TokenInfo(
type = tokenize.NUMBER,
string = str(value),
start = token.start,
end = token.end,
line = token.line
)
yield token
def python_change_default_base(string, base):
tokens = tokenize.tokenize(BytesIO(string.encode()).readline)
transformed = tokens_with_base(tokens, base)
return tokenize.untokenize(transformed)
eval(python_change_default_base("3*2+1/20", 16))
#>>> 6.03125
0x3*0x2+0x1/0x20
#>>> 6.03125
这样更安全,因为它尊重字符串之类的东西。
【讨论】: