Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 oct() Function

The Python oct() function

Python3 Built-in Functions Python3 built-in 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

- Type: integer - Description: the integer to convert to octal.

Function description


Example

Example 1: basic usage

Example

Basic conversions

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:

  1. The returned string starts with "0o" (lowercase letter o), indicating octal.
  2. Each octal digit can represent the eight values 0-7.

Example 2: comparison with hexadecimal and binary

Example

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 the prefix

print

(

f

"Octal (no prefix): {oct(n)[2:]}"

)

print

(

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 Functions Python3 built-in function