解析整数时Python令牌生成器的奇怪行为 [英] Odd behaviour of Python tokenizer when parsing integer numbers

查看:227
本文介绍了解析整数时Python令牌生成器的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到CPython3和Pypy3的以下事实,与CPython2和Pypy2的行为形成对比:

I noticed the following fact with CPython3 and Pypy3, contrasting with the behaviour of both CPython2 and Pypy2:

在Python3中,当解析代码产生错误时,它看起来像前导零,除了一个非常小的数字,即为0 .因此,00有效,但042无效.

In Python3, it looks like leading zeros when parsing code yield an error except for a very single number wich is 0. Thus 00 is valid but not 042.

在Python2中,所有整数都允许前导零.因此00042是有效的.

In Python2, leading zeros are allowed for all integers. Thus 00 and 042 are valid.

为什么Python会在两个版本之间更改其行为?

Why did Python change its behaviour between both versions?

推荐答案

Python 3标准化了如何定义所有整数文字(以10为底的整数):0?dddd...,其中?是表示底数的单个字母,并且每个d在适当的基数中均被解释为数字. 0...被保留为例外,因为0在任何基数中均为0,并且在需要显式基数说明符之前就被接受.

Python 3 standardized how all integer literals (other than base 10) were defined: 0?dddd..., where ? is a single letter indicating the base, and each d is interpreted as a digit in the appropriate base. 0... was retained as an exception, since 0 is 0 in any base, and was accepted as such before explicit base specifiers were required.

与此相关的最大变化是,不再将具有前导零但没有明确的基本说明符的数字视为八进制数. Python 2接受0420o42作为十进制34的八进制表示.(在Python的历史早期,只有三个有效的文字,十六进制是唯一一个带有说明符的文字.0o...0b...都是以后添加

The biggest change related to this is that a number with a leading zero but no explicit base specifier is no longer assumed to be an octal number. Python 2 accepts both 042 and 0o42 as octal representations of decimal 34. (Early in Python's history, there were only three valid literals, with hexadecimal being the only one with a specifier. 0o... and 0b... were both later additions

这篇关于解析整数时Python令牌生成器的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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