The oct(x) built-in function converts an integer number into its base-8 octal string representation prefixed with "0o".
Base-8 Conversion & __index__ Protocol: oct() accepts standard integers or any custom object that implements the __index__() dunder method. To format octal values without the leading "0o" prefix, use format() with specifier 'o'. To convert integers into binary or hexadecimal strings, see companion functions bin() and hex().
The oct() function accepts an integer or indexable object and returns a string:
# Formal syntax of built-in oct()
octal_str = oct(x)
| Parameter | Type Accepted | Behavioral Details |
|---|---|---|
x |
int or object with __index__() |
An integer number. Floats raise a TypeError. |
| Return Value | str |
A lowercase string representing the octal value prefixed with "0o" (e.g. "0o33"). |
Standard decimal integers are converted directly into base-8 strings. Negative integers preserve their leading minus sign before the prefix:
# 1. Converting integer values to octal strings
my_num = 27
print("oct(27):", oct(my_num)) # 0o33
# 2. Converting negative integers
print("oct(-27):", oct(-my_num)) # -0o33
# 3. Converting zero
print("oct(0): ", oct(0)) # 0o0
Output:
oct(27): 0o33
oct(-27): -0o33
oct(0): 0o0
Because Python treats all integer literals identically in memory regardless of source notation, binary (0b...) and hexadecimal (0x...) literals pass directly into oct():
# Inter-base conversions in Python
# Integer 27 represented in different numeric literal bases:
dec_val = 27
bin_val = 0b11011
hex_val = 0x1b
print("Binary to Octal: ", oct(bin_val)) # 0o33
print("Hexadecimal to Octal:", oct(hex_val)) # 0o33
print("Decimal to Octal: ", oct(dec_val)) # 0o33
Output:
Binary to Octal: 0o33
Hexadecimal to Octal: 0o33
Decimal to Octal: 0o33
If your application requires raw octal digits without the "0o" prefix, avoid clumsy string slicing by using built-in format() or f-string specifiers:
# Stripping the '0o' prefix vs. using format() and f-strings
number = 27
# Method 1: Slicing the output string
raw_oct = oct(number)
stripped = raw_oct[2:] if not raw_oct.startswith('-') else '-' + raw_oct[3:]
print("Sliced string: ", stripped)
# Method 2: format() built-in function
print("format(27, 'o'):", format(number, 'o'))
# Method 3: Modern f-string specifier
print("f'{27:o}': ", f"{number:o}")
print("f'{27:#o}': ", f"{number:#o}") # Keeps '0o' prefix
Output:
Sliced string: 33
format(27, 'o'): 33
f'{27:o}': 33
f'{27:#o}': 0o33
Any user-defined class can support oct() by implementing the special method __index__(), returning a concrete integer:
# Custom classes implementing the __index__() dunder method
class FilePermission:
def __init__(self, mode: int):
self.mode = mode
def __index__(self) -> int:
return self.mode
perm = FilePermission(0o755)
print("Type of perm: ", type(perm))
print("oct(perm) via __index__():", oct(perm))
Output:
Type of perm:
oct(perm) via __index__(): 0o755
Because octal digits map directly to groups of three binary bits (0b000 to 0b111), octal literals are ideal for constructing and inspecting binary bitmasks in systems programming:
# Recipe C: Bitwise masking and permission flag extraction
# POSIX mode bits: 0o100755 represents a regular file (-rwxr-xr-x)
mode = 0o100755
# Extract file type mask (0o170000)
file_type_mask = mode & 0o170000
print("File type mask: ", oct(file_type_mask))
# Extract user permission bits (0o700)
user_perms = (mode & 0o700) >> 6
print("User permission value:", oct(user_perms)) # 0o7 (rwx)
Output:
File type mask: 0o100000
User permission value: 0o7
In operating systems and security administration, POSIX file permissions are represented as 3-digit octal codes:
# Recipe A: Linux POSIX file permission decoder
import stat
mode_code = 0o755 # rwxr-xr-x
print("Octal file mode: ", oct(mode_code))
def decode_octal_permissions(octal_val: int) -> str:
perms = ["---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"]
digits = [int(d) for d in f"{octal_val:o}"[-3:]]
return "".join(perms[d] for d in digits)
print("Decoded symbols: ", decode_octal_permissions(mode_code))
# Recipe B: Converting octal string back to decimal integer
oct_repr = "0o755"
decimal_val = int(oct_repr, 8)
print("int('0o755', 8): ", decimal_val)
Output:
Octal file mode: 0o755
Decoded symbols: rwxr-xr-x
int('0o755', 8): 493
oct(). Explicitly truncate or round with int(floor(num)) first.0755 was allowed in Python 2 but causes a SyntaxError in Python 3. Always write 0o755 with the explicit '0o' prefix.int(s, 8).# Pitfall 1: Float inputs raise TypeError
try:
oct(27.45)
except TypeError as err:
print("TypeError caught:", err)
# Pitfall 2: Python 2 legacy '033' octal syntax is a SyntaxError in Python 3!
# Writing literal 033 raises SyntaxError: leading zeros in decimal integer literals are not permitted
# Always write 0o33 with the '0o' prefix!
valid_octal = 0o33
print("Valid Python 3 literal:", valid_octal)
Output:
TypeError caught: 'float' object cannot be interpreted as an integer
Valid Python 3 literal: 27
Practice base conversions, custom `__index__` classes, and Linux permission decoding in our companion Jupyter Notebook:
Explore interactive code cells, decode POSIX permission bits, test format specifiers, and run self-validating assertions.
View on GitHub Run in Google ColabRun these unit checks directly in Python or your local environment to verify oct() mechanics:
def test_oct_mechanics():
# 1. Standard integers
assert oct(27) == "0o33"
assert oct(-27) == "-0o33"
assert oct(0) == "0o0"
# 2. Inter-base inputs
assert oct(0b11011) == "0o33"
assert oct(0x1b) == "0o33"
# 3. int(s, 8) inverse round-trip
assert int(oct(500), 8) == 500
# 4. Custom __index__ object
class Box:
def __index__(self):
return 8
assert oct(Box()) == "0o10"
print("All oct() unit assertions passed! 100% verified.")
test_oct_mechanics()
Output:
All oct() unit assertions passed! 100% verified.
Converts an integer to a binary string prefixed with 0b.
Converts an integer to a hexadecimal string prefixed with 0x.
Parses integer representations across arbitrary bases (2 to 36).
Formats values using standard string and number formatting syntax.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.