python中以0开头的数字是什么意思? [英] What do numbers starting with 0 mean in python?

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

问题描述

当我在 python 中输入前面带有 0 的小整数时,它们给出了奇怪的结果.这是为什么?

<预><代码>>>>0119>>>010064>>>02723

我使用的是 Python 2.7.3.我已经在 Python 3.0 中对此进行了测试,显然这是一个错误.所以它是特定于版本的.

它们显然仍然是整数:

<预><代码>>>>类型(027)<输入'int'>

解决方案

这些是用基数 8(八进制数)表示的数字.一些例子:

Python 2(旧格式)

注意:这些表单仅适用于 Python 2.x.

011 等于 1⋅8¹ + 1⋅8⁰ = 9,

0100 等于 1⋅8² + 0⋅8¹ + 0⋅8⁰ = 64,

027 等于 2⋅8¹ + 7⋅8⁰ = 16 + 7 = 23.

Python 3(新格式)

在 Python 3 中,必须使用 0o 而不是 0 来表示八进制常量,例如0o110o27 等.Python 2.x 版本 >= 2.6 支持新旧格式.

0o11 等于 1⋅8¹ + 1⋅8⁰ = 9,

0o100 等于 1⋅8² + 0⋅8¹ + 0⋅8⁰ = 64,

0o27 等于 2⋅8¹ + 7⋅8⁰ = 16 + 7 = 23.

When I type small integers with a 0 in front into python, they give weird results. Why is this?

>>> 011
9
>>> 0100
64
>>> 027
23

I'm using Python 2.7.3. I have tested this in Python 3.0, and apparently this is now an error. So it is something version-specific.

They are apparently still integers:

>>> type(027)
<type 'int'>

解决方案

These are numbers represented in base 8 (octal numbers). Some examples:

Python 2 (old format)

Note: these forms only work on Python 2.x.

011 is equal to 1⋅8¹ + 1⋅8⁰ = 9,

0100 is equal to 1⋅8² + 0⋅8¹ + 0⋅8⁰ = 64,

027 is equal to 2⋅8¹ + 7⋅8⁰ = 16 + 7 = 23.

Python 3 (new format)

In Python 3, one must use 0o instead of just 0 to indicate an octal constant, e.g. 0o11 or 0o27, etc. Python 2.x versions >= 2.6 supports both the new and the old format.

0o11 is equal to 1⋅8¹ + 1⋅8⁰ = 9,

0o100 is equal to 1⋅8² + 0⋅8¹ + 0⋅8⁰ = 64,

0o27 is equal to 2⋅8¹ + 7⋅8⁰ = 16 + 7 = 23.

这篇关于python中以0开头的数字是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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