oct()

oct(x)
Returns: str · Added in v3.0 · Updated March 13, 2026 · Built-in Functions
conversion built-in octal formatting

The oct() function converts an integer to its octal (base-8) string representation. The output always includes the 0o prefix, that Python uses for octal literals. Use it for file permissions, low-level system programming, and other octal representations.

Syntax

oct(x)

Parameters

ParameterTypeDescription
xintAn integer to convert to octal. Can be positive, negative, or zero.

Examples

Basic usage

>>> oct(8)
'0o10'
>>> oct(10)
'0o12'
>>> oct(16)
'0o20'

Working with negative numbers

>>> oct(-8)
'-0o10'
>>> oct(-1)
'-0o1'

Practical example: file permissions

File permissions in Unix are represented as octal numbers. You can use oct() to convert decimal permission values:

# Standard Unix file permissions
read_only = 0o400      # Owner read
write_execute = 0o755   # rwxr-xr-x
private = 0o600        # rw-------

print(oct(read_only))      # '0o400'
print(oct(write_execute))  # '0o755'
print(oct(private))        # '0o600'

Converting between number bases

>>> # Convert decimal to octal
>>> oct(42)
'0o52'

>>> # Convert back using int with base
>>> int('0o52', 8)
42

Common Patterns

Using with format strings

num = 64
print(f"Decimal: {num}, Octal: {oct(num)}")
# Output: Decimal: 64, Octal: 0o100

Reading octal from strings

To convert an octal string back to an integer, use int() with base 8:

>>> int('0o755', 8)
493
>>> int('755', 8)
493

Errors

oct() raises a TypeError if the argument is not an integer:

>>> oct(3.14)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer

>>> oct('10')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer

See Also