Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python oct() function

Reference for Python oct(): convert an integer to an octal string with the 0o prefix, strip the prefix, parse octal back and use it for file permissions.

The built-in oct() function converts an integer to a string of its octal (base 8) representation, prefixed with 0o. The result is a valid Python literal, so eval(oct(n)) == n would hold, although you should never need eval for that.

Octal is most familiar from Unix file permissions: 0o755 means read/write/execute for the owner and read/execute for everyone else.

Python
oct(8)     # "0o10"
oct(255)   # "0o377"
oct(-8)    # "-0o10"

Try it

Python Integers to octal and back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Permissions and formatting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
oct(x)
Name Description
x An int, or an object whose class defines __index__() returning an int.

Return value: a str such as "0o17"; negative numbers get a leading minus sign: "-0o17".

Raises: TypeError for floats, strings and other non-integers (oct(8.0) fails).

Usage notes

  • The 0o prefix is part of the string. Slice it off with [2:] for positive numbers, or use format(n, "o") / f"{n:o}", which omit the prefix and handle negatives correctly. "#o" keeps the prefix.
  • Zero-padding comes from format specs: f"{n:04o}" pads to four digits.
  • Back to an int: int(text, 8) accepts digits with or without 0o. int(text, 0) requires the prefix and picks the base from it.
  • Old-style literals are gone. In Python 2, 0755 was octal; in Python 3 it is a syntax error. Write 0o755.
  • Floats are rejected. Convert with int() first if you really mean to.
  • Custom classes can support oct() by defining __index__().
  • Permissions in os.chmod take an integer, so write the literal (0o600), not a string.
  • Related functions: bin() and hex() do the same for base 2 and base 16.