Hex() Function In Python

Function Name:



Function Signature:



Function Overview:

The python function hex() converts an integer value of 

  • Decimal format
  • Octal format
  • Hexadecimal format

into Hexadecimal format and returns the string that contains the Hexdecimal form.


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



# A class that defines the __index__() method

class NumClass:

    def __init__(self, val):

        self.myVal = val


    def __index__(self):

        return self.myVal


# Convert decimal form to hexadecimal form

decimalNumber       = 33

hexaDecimalString   = hex(decimalNumber)

print("Decimal form to Hexadecimal form:{}".format(hexaDecimalString))


# Convert octal form to hexadecimal form

octalNumber         = 0o33

hexaDecimalString   = oct(octalNumber)

print("Octal form to  Hexadecimal form:{}".format(hexaDecimalString))


# Convert an object that has the __index__() implemented

numericObject       = NumClass(33)

hexaDecimalString   = oct(numericObject)

print("Object with __index__() to Hexadecimal form:{}".format(hexaDecimalString))




Decimal form to Hexadecimal form:0x21

Octal form to  Hexadecimal form:0o33

Object with __index__() to Hexadecimal form:0o41


Copyright 2022 © pythontic.com