Python 无法处理以 0 开头的数字字符串.为什么? [英] Python cannot handle numbers string starting with 0. Why?

查看:132
本文介绍了Python 无法处理以 0 开头的数字字符串.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在我的 python 解释器上执行了以下程序:

<预><代码>>>>定义我的生活(x):...如果x>0:...打印(x)... 别的:...打印(-x)...>>>我的生活(01)文件<stdin>",第 1 行我的生活(01)^语法错误:无效的令牌>>>我的生活(1)1>>>我的生活(-1)1>>>我的生活(0)0

现在,我已经看到了这个但是正如链接所说,八进制的 0 在 python 中不再起作用(即在 python3 中不起作用).但这不意味着应该正确解释以 0 开头的数字的行为吗?以 base-2 还是以正常的 base-10 表示?既然不是这样,为什么python会这样呢?这是一个实施问题吗?还是语义问题?

解决方案

我的猜测是,由于 012 在 python3.x 中不再是八进制文字常量,他们不允许 012 语法以避免奇怪的向后兼容性错误.考虑使用八进制文字常量的 python2.x 脚本:

a = 012 + 013

然后你将它移植到 python 3,它仍然有效——它只是给你 a = 25 而不是你之前预期的 a = 21 (十进制).追踪那个错误很有趣.

I just executed the following program on my python interpreter:

>>> def mylife(x):
...     if x>0:
...             print(x)
...     else:
...             print(-x)
... 
>>> mylife(01)
File "<stdin>", line 1
mylife(01)
        ^
SyntaxError: invalid token
>>> mylife(1)
1
>>> mylife(-1)
1
>>> mylife(0)
0

Now, I have seen this but as the link says, the 0 for octal does not work any more in python (i.e. does not work in python3). But does that not mean that the the behaviour for numbers starting with 0 should be interpreted properly? Either in base-2 or in normal base-10 representation? Since it is not so, why does python behave like that? Is it an implementation issue? Or is it a semantic issue?

解决方案

My guess is that since 012 is no longer an octal literal constant in python3.x, they disallowed the 012 syntax to avoid strange backward compatibility bugs. Consider your python2.x script which using octal literal constants:

a = 012 + 013

Then you port it to python 3 and it still works -- It just gives you a = 25 instead of a = 21 as you expected previously (decimal). Have fun tracking down that bug.

这篇关于Python 无法处理以 0 开头的数字字符串.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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