The Python oct() function
oct() is a built-in Python function that converts an integer to an octal string.
Octal is a commonly used number representation in computing, with digits 0-7 representing values.oct() The function returns an octal string starting with "0o".
Word meaning: oct is short for octal.
Basic syntax and parameters
Syntax format
oct(x)
Parameter Description
- Parameter x:
- Type: integer
- Description: the integer to convert to octal.
Function description
- Return Value: returns an octal string starting with "0o".
Example
Example 1: basic usage
Example
Basic conversions
(
oct
(
8
)
)
Output: 0o10
(
oct
(
9
)
)
Output: 0o11
(
oct
(
64
)
)
Output: 0o100
(
oct
(
255
)
)
Output: 0o377
Negative numbers
(
oct
(
8
)
)
Output: -0o10
zero
(
oct
(
0
)
)
Output: 0o0
1-7
for
i
in
range
(
1
,
8
)
:
(
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 letter o), indicating octal.
- Each octal digit can represent the eight values 0-7.
Example 2: comparison with hexadecimal and binary
Example
n
=
64
Different base representations
(
f
"Decimal: {n}"
)
(
f
"Binary: {bin(n)}"
)
(
f
"Octal: {oct(n)}"
)
(
f
"Hexadecimal: {hex(n)}"
)
Remove the prefix
(
f
"Octal (no prefix): {oct(n)[2:]}"
)
(
f
"Hexadecimal (no prefix): {hex(n)[2:]}"
)
Expected output:
十进制: 64
二进制: 0b1000000
八进制: 0o100
十六进制: 0x40
Python provides the bin()、oct()、hex() Three functions are used to convert between different bases.
Python3 built-in function