Search code examples
pythonfunctionoctal

Python oct() function missing expected 0oXXXX prefix?


Not sure if this is a system or version thing, but I am missing my expected octal prefix when calling the embedded oct() function? Here's my example

# Base conversion operations
print 'x = 1234 ' ; x = 1234                # all numbers are base10 derivs
print 'bin(x) '   , bin(x)                  # '0b10011010010'
print 'oct(x) '   , oct(x)                  # '02322' -> missing prefix??? expected: 0o02322???
print 'hex(x) '   , hex(x)                  # '0x4d2'

# Using the format() function to suppress prefixes
print 'format(x, \'b\')' , format(x, 'b')   # bin conversion
print 'format(x, \'o\')' , format(x, 'o')   # oct conversion
print 'format(x, \'x\')' , format(x, 'x')   # hex conversion

# version: Python 2.7.13
# output:
# x = 1234
# bin(x)  0b10011010010
# oct(x)  02322               <- unexpected output
# hex(x)  0x4d2
# format(x, 'b') 10011010010
# format(x, 'o') 2322
# format(x, 'x') 4d2

I would very well expect a return from python -c "print oct(1234)" to be '0o02322' or am I missing something obvious?

Walking down the definition for oct from __builtin__.py__

def oct(number): # real signature unknown; restored from __doc__
  """
  oct(number) -> string

  Return the octal representation of an integer or long integer.
  """
  return ""

returning the octal rep of an int should express a prefixed string?


Solution

  • Before Python 2.6, only 0XXXXX octal representation was allowed. In Python 3.x, only 0oXXXXX octal representation is allowed.

    To make it easy to migration from Python 2.x to Python 3.x, Python 2.6 added support for 0oXXXX. See PEP 3127: Integer Literal Support and Syntax - What's new in Python 2.6.

    >>> 0o1234 == 01234  # ran in Python 2.7.13
    True
    

    Behavior of oct in Python 2.x didn't change for backward compatibility.

    If you want you can define your own version of oct:

    >>> octal = '{:#o}'.format
    >>> octal(10)
    '0o12'