Python oct()
is a built-in function that returns the octal representation of an integer and the octal value is prefixed with '0o'
.
oct(num)
Python oct()
function takes only one parameter as an argument.
Note: If num
is not a Python integer object, it has to define an __index__()
method that returns an integer.
>>> #binary numbers
>>> oct(0b10101)
'0o25' #corresponding octal string
>>> #decimal numbers
>>> oct(55)
'0o67' #corresponding octal string
>>> #Hexadecimal numbers
>>> oct(0XAB)
'0o253' #corresponding octal string
In above example, you can see the octal conversion of simple numerals.
Now, let’s see how we can use Python oct()
function for custom objects.
class Employee:
salary = 45000
def __index__(self):
return self.salary
#Use __int__() method for older version's compatibility
def __int__(self):
return self.salary
#Creating a new object of class Employee
emp_salary = Employee()
print('Salary in Octal is:', oct(emp_salary))
Output
Salary in Octal is: 0o127710
Here instead of passing integer value, we have supplied a custom object of class Employee
to convert salary into octal value.
Now some of you may wonder if there is any way to use oct()
function without the prefix 0o
. Well yes, there is a way.
This is achieved by truncating the first two character of the output. This might remove the perfixing 0o
but we do not recommend doing this in real time programs.
>>> oct(0XAB)[2:]
'253'
>>> hex(22)[2:]
'26'
Note that this method will break in negative values of the parameter.
Here is the example.
>>> oct(-25)
'-0o31'
>>> #Now using [2:]
>>> oct(-25)[2:]
'o31'
This is because we are truncating only first two characters, hence only -
and 0
gets removed and o
remains there.
So, for negative values 3
should be used instead of 2
.
>>> oct(-25)[3:]
'31'