Python oct()
Python oct() builtin function is used to convert an integer to octal string prefixed with ‘Oo’.
In this tutorial, we will learn about the syntax of Python oct() function, and learn how to use this function with the help of examples.
Syntax
The syntax of oct() function is
oct(x)
where
Parameter | Required/ Optional | Description |
---|---|---|
x | Required | An integer. Or an object that defines __index__() method and returns an integer. |
Returns
The function returns string object.
Examples
1. Octal String for Integer
In this example, we take an integer in x
, and convert it into octal string using oct() function.
Python Program
x = 144
result = oct(x)
print(result)
Output
0o220
2. Octal String for Class Object
In this example, we define a class A
, with __index__() method that returns hash of this class instance (an integer). and convert it into octal string using oct() function.
Python Program
class A:
def __index__(self):
return hash(self)
result = oct(A())
print(result)
Output
0o2001345361
Conclusion
In this Python Tutorial, we have learnt the syntax of Python oct() builtin function, and also learned how to use this function, with the help of Python example programs.