oct() function in Python

The python oct() function converts an integer of the form decimal, hexa-decimal, octal to a string containing the octal value of the integer

Built-in Functions Updated 28 Feb 2017 1 min read

Function Name

oct()

Function Signature

oct(intVal)

Function Overview

The python function oct() converts an integer value of

  • Decimal format
  • Hexa-decimal format
  • Octal format

into octal format and returns the string that contains the octal form.

As long as __index__() method is defined for a python object - the oct() function will convert the integer returned by the __index__() method into the octal form.

Example

python
# A class that defines the __inedx__() method

class SpecialClass:

    def __init__(self, val):

        self.myVal = val

    def __index__(self):

        return self.myVal

# Convert decimal form to octal form

decimalNumber   = 33

octalString     = oct(decimalNumber)

print("Decimal form to Octal form:{}".format(octalString))

# Convert hexa-decimal form to octal form

hexaDecimalNumber   = 0x33F

octalString         = oct(hexaDecimalNumber)

print("Hexa-decimal form to Octal form:{}".format(octalString))

# Convert an object that has the __index__() implemented

numericObject       = SpecialClass(33)

octalString         = oct(numericObject)

print("Object with __index__() to Octal form:{}".format(octalString))

Output

Output
Decimal form to Octal form:0o41

Hexa-decimal form to Octal form:0o1477

Object with __index__() to Octal form:0o41