Skip to Content

Python – Convert Integer to Octal

In this tutorial, we will look at how to convert an integer to an octal string in Python with the help of some examples.

How to convert integer to octal in Python?

You can use the Python built-in oct() function to convert an integer to its octal form in Python. Pass the integer as an argument to the function. The following is the syntax –

# convert int i to octal
oct(i)

It returns the integer’s representation in the octal number system (base 8) as a lowercase string prefixed with '0o'.

Examples

Let’s look at some examples of using the above function to convert int to oct.

Positive integer to hexadecimal

Pass the integer as an argument to the oct() function.

# int variable
num = 11
# int to oct
num_oct = oct(num)
# display oct and type
print(num_oct)
print(type(num_oct))

Output:

0o13
<class 'str'>

You can see that we get the octal representing the integer as a string with '0o' prefix.

If you do not want the prefix, you can use the string slice operation to remove the prefix from the returned octal string.

Negative integer to hexadecimal

Let’s now apply the same function to a negative integer.

# int variable
num = -11
# int to oct
num_oct = oct(num)
# display oct and type
print(num_oct)
print(type(num_oct))

Output:

-0o13
<class 'str'>

We get its octal string.

Integer to uppercase hexadecimal string

Alternatively, you can use the Python built-in format() function to convert an integer to its octal form. You can also customize the format of the returned string.

For example, to convert an integer to an octal string with the prefix, use the format string '#o'.

# int variable
num = 11
# int to oct
num_oct = format(num, '#o')
# display oct and type
print(num_oct)
print(type(num_oct))

Output:

0XF
<class 'str'>

We get the octal for the integer as a string with the prefix '0o'.

With the format() function you can customize the returned octal string – with or without the prefix.

# int variable
num = 11
# int to oct
print(f"Octal with prefix: {format(num, '#o')}")
print(f"Octal without prefix: {format(num, 'o')}")

Output:

Octal with prefix: 0o13
Octal without prefix: 13

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush

    Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.