Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7 str(055) returns "45" instead of 055 [duplicate]

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

>>> str(055)
'45'
like image 669
user3246739 Avatar asked Dec 19 '22 18:12

user3246739


1 Answers

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.

like image 198
Ashwini Chaudhary Avatar answered Dec 22 '22 07:12

Ashwini Chaudhary