Python 2.7 str(055) 返回“45";而不是 055 [英] Python 2.7 str(055) returns "45" instead of 055

查看:52
本文介绍了Python 2.7 str(055) 返回“45";而不是 055的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我在 python 2.7 中得到以下结果,而不是055"?

<预><代码>>>>字符串(055)'45'

解决方案

055 是一个八进制数,十进制等效为 45,使用 oct> 以获得正确的输出.

<预><代码>>>>十月(055)'055'

Python 2.X 中的八进制数语法:

octinteger ::= "0" ("o" | "O") octdigit+ |0"八位数字+

但这只是为了表示目的,最终它们总是被转换为整数以进行存储或计算:

<预><代码>>>>x = 055>>>X45>>>x = 0xff #十六进制>>>X255>>>x = 0b111 # 二进制>>>X7>>>0xff * 05511475

注意,在 Python 3.x 中,八进制数现在由 0o 表示.因此,使用 055 会引发 SyntaxError.

Why I get the following result in python 2.7, instead of '055'?

>>> str(055)
'45'

解决方案

055 is an octal number whose decimal equivalent is 45, use oct to get the correct output.

>>> oct(055)
'055'

Syntax for octal numbers in Python 2.X:

octinteger     ::=  "0" ("o" | "O") octdigit+ | "0" octdigit+

But this is just for representation purpose, ultimately they are always converted to integers for either storing or calculation:

>>> x = 055
>>> x
45
>>> x = 0xff   # HexaDecimal
>>> x
255
>>> x = 0b111  # Binary
>>> x
7
>>> 0xff * 055
11475

Note that in Python 3.x octal numbers are now represented by 0o. So, using 055 there will raise SyntaxError.

这篇关于Python 2.7 str(055) 返回“45";而不是 055的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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