Python oct() Method

The oct() method converts an integer, binary, and hexadcimal to octal string prefixed with "0o".

Syntax:

oct(value)

Parameters:

value: An integer.

Return Value:

Returns an octal string prefixed with "0o".

The following example converts various values into their octal equivalent.

Example: oct()
print("Integer 10 to octal: ", oct(15))
print("Binary 0b1010 to octal: ", oct(0b1110))
print("Hexadecimal 0x15 to octal: ", oct(0x15))
Output
Integer 10 to octal: '0o17'
Binary 0b1110 to octal:  '0o16'
Hexadecimal 0x15 to octal:  '0o25'

The oct() function will throw an error if the specified value is not an integer. If the specified parameter is not an integer value, then that class has to define an __index__() method that returns an integer.

Example: oct()
class Student:
    age = 15

    def __index__(self):
        return self.age
        
std = Student()
print(oct(std))
Output
'0o17'
Want to check how much you know Python?