Python oct()

In this post, we will see about Python oct() function.
Python oct() method converts an int to octal string with ‘0o’ as prefix.If x is not an Python int then it needs to define __index__ method which returns an int.


Syntax

x is the int which you want to convert to octadecimal


Return

It returns octadecimal representation of int.


Example

Let’s understand with help of simple example:

print('Octal String representation of 9:',oct(9)) print('Octal String representation of 13:',oct(13)) print('Octal String representation of 101:',oct(101))

Output:

Octal String representation of 9: 0o11
Octal String representation of 13: 0o15
Octal String representation of 101: 0o145

oct() for user defined class

You need to implement __index__() method which returns an int in case of user defined class.We are simply returning 26 from below __index__() and when you call oct(country), it internally executes __index__() of country class only.

class Country: name = 'India' population = 10000 def __index__(self): return 26 country = Country() print(oct(country))

Output:

0o32

That’s all about oct() function in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *