4

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

>>> str(055)
'45'
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • 2
    just entering `055` without the `str` returns `45` as well, fyi – mhlester Jan 28 '14 at 23:41
  • 1
    [What do numbers starting with 0 mean in python?](http://stackoverflow.com/questions/11620151/what-do-numbers-starting-with-0-mean-in-python) – sachleen Jan 28 '14 at 23:41
  • Note that `str(1 2 3)` is a syntax error, and `str(asdf)` won't produce `'asdf'` unless `asdf` is a variable containing `'asdf'`. The argument to `str` is evaluated as an ordinary Python expression; it's not like putting quotation marks around something. – user2357112 Jan 28 '14 at 23:50

1 Answers1

11

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.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504