oct()

The built-in oct() function converts a given integer into its octal string representation, prefixed with 0o. The function’s output is a string:

Python
>>> oct(42)
'0o52'

oct() Signature

Python Syntax
oct(x)

Arguments

Argument Description
x An integer value or an object that defines an .__index__() method returning an integer

Return Value

  • Returns a string holding the octal representation of the input integer. If the integer is negative, the string will include the negative sign.

oct() Examples

With a positive integer as an argument:

Python
>>> oct(8)
'0o10'

With a negative integer as an argument:

Python
>>> oct(-56)
'-0o70'

With an object of a class with a .__index__() method:

Python
>>> class Number:
...     def __init__(self, value):
...         self.value = value
...     def __index__(self):
...         return self.value
...

>>> number = Number(10)
>>> oct(number)
'0o12'

oct() Common Use Cases

The most common use cases for the oct() function include:

  • Converting decimal numbers to their octal representation for use in systems or applications that require octal numbers
  • Formatting output to display numbers in octal format
  • Preparing data for systems that operate primarily on octal numbers, such as some file permission systems in Unix

oct() Real-World Example

Say you’re working on a Unix-like system and need to display file permissions in octal format for auditing purposes. You can use oct() to convert permission values to octal:

Python
>>> permissions = 493
>>> f"File permissions in octal: {oct(permissions)}"
'File permissions in octal: 0o755'

In this example, the oct() function helps you convert numeric file permissions into a human-readable octal format, which is commonly used in Unix-based systems.

Tutorial

Python's Built-in Functions: A Complete Exploration

In this tutorial, you'll learn the basics of working with Python's numerous built-in functions. You'll explore how to use these predefined functions to perform common tasks and operations, such as mathematical calculations, data type conversions, and string manipulations.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 21, 2024 • Reviewed by Dan Bader