Python 2.7 str(055) returns "45" instead of 055

python, python-2.7, string

Solution

`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`.

Problem

Why I get the following result in python 2.7, instead of '055'? ``` >>> str(055) '45' ```

Original source

Related problems