In Python, oct(x) converts an integer to an octal (base 8) string with the prefix 0o: oct(8) returns '0o10'. Each octal digit stands for exactly three bits.
Octal is most common for Unix file permissions, where 0o755 means read/write/execute for the owner and read/execute for everyone else. In source code you write octal numbers with the same 0o prefix.
oct() is a built-in function: it lives in the builtins module, so it is always available without an import.
Syntax
Pass an int; you get octal text.
python
text = oct(number) # '0o...'
Call
What it does
oct(8)
Returns '0o10'.
oct(493)
Returns '0o755'.
format(493, "o")
Returns '755' without the prefix.
int("755", 8)
Returns 493.
Python 3 does not accept old-style octal literals like 0755; you must write 0o755.
Library declarations
python
oct(x, /)
# x: int, or an object with __index__()
Parameters
Parameter
Description
x
Required. An int or an object with __index__().
Return Value
Return Value
Description
str
Octal digits prefixed with 0o (or -0o).
Python Examples
Example 1 — Octal Strings for Several Integers
Convert a few integers and notice how each octal place is a power of 8.
python
for n in [8, 64, 100, 511, -8]:
print(n, oct(n))
Output
8 0o10
64 0o100
100 0o144
511 0o777
-8 -0o10
How It Works
Powers of 8. 8 is written 10 and 64 (8 * 8) is 100 in octal.
Mixed digits. 100 is 1 * 64 + 4 * 8 + 4, which reads as 144.
Largest three digits. 511 is 777: nine 1 bits, three per octal digit.
Negatives. The minus sign goes in front of the prefix: -0o10.
Example 2 — Read Unix Permission Bits
Split the classic 0o755 mode into owner, group, and others, and test a flag from the stat module.