Python oct()

Filed Under: Python

Python oct() function is used to convert an integer into octal string prefixed with “0o”.

Python oct()

Python oct() function syntax is:


oct(x)

The output of oct() function is a string. We can pass an object as an argument too, in that case, the object must have __index__() function implementation that returns integer.

Let’s look at some simple examples of oct() function.


print(oct(10))

print(oct(0xF))

print(oct(0b1111))

print(type(oct(10)))

Output:


0o12
0o17
0o17
<class 'str'>

Python oct() with object

Let’s look at another example where we will use oct() function with a custom object as an argument. We will implement __index__() function in this object.


class Data:
    id = 0

    def __init__(self, i):
        self.id = i

    def __index__(self):
        return self.id


d = Data(20)

print(oct(d))

Output: 0o24

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages