Python oct() Function
oct()Is a built-in function in Python used to convert integers to octal strings.
Octal is a common base representation in computers, with digits 0-7 representing values.oct()The function returns an octal string starting with "0o".
Word Definition: octIs the abbreviation for octal.
Basic Syntax and Parameters
Syntax
oct(x)
Parameter Description
- Parameter x:
- Type: Integer
- Description: The integer to be converted to octal.
Function Description
- Return value: Returns an octal string starting with "0o".
Examples
Example 1: Basic Usage
Examples
# Basic Conversion
print(oct(8)) # Output: 0o10
print(oct(9)) # Output: 0o11
print(oct(64)) # Output: 0o100
print(oct(255)) # Output: 0o377
# Negative numbers
print(oct(-8)) # Output: -0o10
# Zero
print(oct(0)) # Output: 0o0
# 1-7
for i in range(1, 8):
print(f"{i} -> {oct(i)}")
# Output: 1 -> 0o1, 2 -> 0o2, ..., 7 -> 0o7
print(oct(8)) # Output: 0o10
print(oct(9)) # Output: 0o11
print(oct(64)) # Output: 0o100
print(oct(255)) # Output: 0o377
# Negative numbers
print(oct(-8)) # Output: -0o10
# Zero
print(oct(0)) # Output: 0o0
# 1-7
for i in range(1, 8):
print(f"{i} -> {oct(i)}")
# Output: 1 -> 0o1, 2 -> 0o2, ..., 7 -> 0o7
Expected output:
0o10 0o11 0o100 0o377 -0o10 0o0 1 -> 0o1 2 -> 0o2 3 -> 0o3 4 -> 0o4 5 -> 0o5 6 -> 0o6 7 -> 0o7
Code analysis:
- The returned string starts with "0o" (lowercase o), indicating octal.
- Each octal digit can represent eight values from 0 to 7.
Example 2: Comparison with Hexadecimal and Binary
Examples
n = 64
# Different base representations
print(f"Decimal: {n}")
print(f"Binary: {bin(n)}")
print(f"Octal: {oct(n)}")
print(f"Hexadecimal: {hex(n)}")
# Remove prefix
print(f"Octal (without prefix): {oct(n)[2:]}")
print(f"Hexadecimal (without prefix): {hex(n)[2:]}")
# Different base representations
print(f"Decimal: {n}")
print(f"Binary: {bin(n)}")
print(f"Octal: {oct(n)}")
print(f"Hexadecimal: {hex(n)}")
# Remove prefix
print(f"Octal (without prefix): {oct(n)[2:]}")
print(f"Hexadecimal (without prefix): {hex(n)[2:]}")
Expected output:
十进制: 64 二进制: 0b1000000 八进制: 0o100 十六进制: 0x40
Python providesbin()、oct()、hex()Three functions to convert between different bases.
Other Extensions
Python3 Built-in Functions